简体   繁体   English

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

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

this is my react code i get an empty result when i console.log(req.body) on my express server (like this-> { body: {} }) i should get all data inside that csv file in my server plz help, thank you in advance这是我的反应代码,当我在我的快递服务器上 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;

Since i have done a similar task today i like to post an answer to help the future readers:) (i also use typescript, tailwindcss(for styling) on the following answer which you can ignore it if you don't use neither of tools.因为我今天做了类似的任务,所以我想发布一个答案来帮助未来的读者:)(我也在下面的答案中使用 typescript,tailwindcss(用于样式),如果你不使用这两种工具,你可以忽略它.


you can use FormData in order to send a csv file in a post request, i think this is the simplest way to send files in a post request.您可以使用 FormData 在发布请求中发送 csv 文件,我认为这是在发布请求中发送文件的最简单方法。

in React you can create a simple form and put an input element with the type="file" inside.在 React 中,您可以创建一个简单的表单并在其中放置一个type="file"的输入元素。 so that your can then use useState hook to save it as a state.这样您就可以使用useState挂钩将其保存为 state。 after saving the file using useState hook you can simply use使用 useState 挂钩保存文件后,您可以简单地使用

formdata.append(name, value) 

and then put the formdata inside the body of axios post request.然后将formdata放入axios post request的正文中。 (as a good practice write onSubmit={handleSubmit} on tag not on the submit button) (作为一个很好的做法,在标签上写 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>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM