使用 React 将 csv 文件作为用户的输入,并使用 axios 将其作为 post 请求发送

take a csv file as input from user using React and send it as a post request using axios

这是我的反应代码,当我在我的快速服务器上 console.log(req.body) 时,我得到一个空结果(像这样-> { body: {} })我应该在我的服务器中获取该 csv 文件中的所有数据请帮助,提前谢谢你

import React, { useState } from 'react';
import axios from 'axios';

const Form = () => {
    const [csvFile, setCSVFile] = useState();

const sendRequst = async () => {
    try {
        const res = await axios.post('http://localhost:4040/inventory/customer-segmentation', { body: csvFile });
    } catch (err) {
        console.log(err);
    }
};

const handleSubmit = (e) => {
    e.preventDefault();
    console.log(csvFile)  (*i get this File {name: 'convertcsv.csv', lastModified: 1636535333170, lastModifiedDate: Wed Nov 10 2021 14:38:53 GMT+0530 (India Standard Time), webkitRelativePath: '', size: 3491, …}*)
    sendRequst();
};


return (
    <div>
        <form onSubmit={handleSubmit}>
            <input
                type='file'
                accept='.csv'
                onChange({(e) => {
                    setCSVFile(e.target.files[0]);
            }}
            />
            <br />
            <button type='submit'>
                Submit
            </button>
        </form>
    </div>
);
};

export default Form;

因为我今天做了一个类似的任务,所以我想 post 一个答案来帮助未来的读者:)如果您不使用这两种工具。


您可以使用 FormData 在 post 请求中发送 csv 文件,我认为这是在 post 请求中发送文件的最简单方法。

在 React 中,您可以创建一个简单的表单并在其中放置一个带有 type="file" 的输入元素。这样您就可以使用 useState 挂钩将其保存为状态。使用 useState 钩子保存文件后,您可以简单地使用

formdata.append(name, value) 

然后将表单数据放入 axios post 请求的主体中。 (作为一个好习惯,在标签上而不是在提交按钮上写 onSubmit={handleSubmit})

const [csvFile, setCsvFile] = useState <Blob>();

const formData = new FormData();

if (csvFile){
 formData.append('path_to_csv', csvFile);
}

const handleChange = (e:React.ChangeEvent<HTMLInputElement>) => {
    if (e.currentTarget.files) setCsvFile(e.currentTarget.files[0]);
};

const handleSubmit = (e:React.FormEvent<HTMLFormElement>) => {
 e.preventDefault();

 async function fetchData() {
 const res:any = await axios.post(
   'http://127.0.0.1:8000/end_point_name_here/',
   formData,
   );
   console.log(res.data);
  }
  fetchData();
};

  return (
      <div className="flex flex-col gap-6 justify-center items-center h-screen">
        <h1> Page Title</h1>
        <form onSubmit={handleSubmit}>
          <input type="file" accept=".csv" onChange={handleChange} />
          <button type="submit" className="bg-blue-500 px-4 py-2 rounded-md font-semibold">fetch</button>
        </form>
      </div>
  );
};