【问题标题】:take a csv file as input from user using React and send it as a post request using axios使用 React 将 csv 文件作为用户的输入,并使用 axios 将其作为发布请求发送
【发布时间】:2022-01-19 21:44:07
【问题描述】:

这是我的反应代码,当我在我的 express 服务器上使用 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;

【问题讨论】:

  • 您的组件中几乎没有错误。首先,react 异步设置状态,因此在实际状态更改之前调用sendRequest。然后,您的变量 csvFile 在状态更改时不会更改。当状态更改时,您的组件将被调用,并且将有一个名为 csvFile 的全新变量。
  • @Mr.Hedgehog 现在我稍微更改了我的代码,现在我得到一个 csv 文件,当我在我的浏览器控制台文件 {name:'convertcsv .csv', lastModified: 1636535333170, lastModifiedDate: Wed Nov 10 2021 14:38:53 GMT+0530 (India Standard Time), webkitRelativePath: '', size: 3491, ...}
  • 现在您需要发送文件。您可以通过多种方式执行此操作。一个是form data 的字段。另一个将在客户端读取文件并将其作为二进制数据发送。然后,由于您的文件本质上是文本,您可以在客户端上阅读它并将其内容作为文本发送。我不知道你到底想要什么,也不知道它是如何用 axios 完成的——我没有用 axios 工作过。

标签: javascript reactjs express csv server


【解决方案1】:

由于我今天完成了类似的任务,因此我想发布一个答案以帮助未来的读者:)(我还在以下答案中使用 typescript、tailwindcss(用于样式),如果您不使用可以忽略它两种工具都没有。


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

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

formdata.append(name, value) 

然后把formdata放到axios post请求的body里面。 (作为一个很好的做法,在标签上写上 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>
  );
};

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2021-10-05
    • 2022-10-21
    • 1970-01-01
    • 2021-02-03
    • 2018-01-03
    相关资源
    最近更新 更多