【问题标题】:Passing a csv file as a parameter to a REST Api in Reactjs将 csv 文件作为参数传递给 Reactjs 中的 REST Api
【发布时间】:2021-10-04 02:08:59
【问题描述】:

我正在解析一个 csv 文件并使用 reactjsRestAPI 从中获取数据。 首先,我使用 reactstrap 在我的网页中添加了一个输入表单。

import React from 'react';
import { FormGroup, Label, Input } from "reactstrap";

export default function UploadParseCsv(props) {
    //posting the csv file to api, for data parsing
  var bodyFormData = new FormData();
  bodyFormData.append("csv_file", csv_file);

  axios({
    method: "post",
    URL: "api_url",
    data: bodyFormData,
    headers: { "Content-Type": "multipart/form-data" },
  })
    .then(function (response) {
      //handle success
      console.log(response);
    })
    .catch(function (response) {
      //handle error
      console.log(response);
    });

   return(
     <div>
       <FormGroup>
          <Input type="file" name="file" id="exampleFile" />
        </FormGroup>
     </div> 
)
}

这就是我当前代码的样子。 我想选择一个 CSV 文件并将其传递给 API 进行解析。 文件上传后,我无法在 Axios 中触发发布请求。 任何帮助将不胜感激!

【问题讨论】:

    标签: javascript html reactjs api axios


    【解决方案1】:

    很简单,我必须编写一个函数来将 csv 文件作为表单数据传递,这里是代码

    import React from 'react';
    import { FormGroup, Label, Input } from "reactstrap";
    
    function UploadParseCsv(props) {
        //posting the csv file to api, for data parsing
      const fileHandler = (event) => {
        const formData = new FormData();
        formData.append("csvFile", event.target.files[0]);
        const config = {
          headers: {
            "content-type": "multipart/form-data",
          },
        };
        axios({
          method: "post",
          url: "myurl",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        })
          .then(function (response) {
            //handle success
            console.log(response);
          })
          .catch(function (response) {
            //handle error
            console.log(response);
          });
      };
    
       return(
         <div>
           <FormGroup>
              <Input 
              type="file"
              name="file" 
              id="exampleFile" 
              onChange={(e) => fileHandler(e)}/>
            </FormGroup>
         </div> 
    )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多