【问题标题】:How can we receive a csv file in server side react hooks web app我们如何在服务器端 React hooks Web 应用程序中接收 csv 文件
【发布时间】:2021-10-09 14:42:01
【问题描述】:

在 react hooks web 应用程序中,我们如何在服务器端接收 csv 文件。以下内容不起作用,因为我在服务器端获取未定义的文件。有人可以建议吗?

server.js

const multer  = require('multer');
const bodyParser = require("body-parser");
const path = require('path');

app.use(express.static(path.join(__dirname, 'public')));

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/csv')
  },
  filename: function (req, file, cb) {
    var ext = file.originalname.split('.').pop();
    cb(null, file.fieldname + '-' + Date.now() + '.' + ext);
  }
})

var upload = multer({ storage: storage });

    app.put('/service/managenominees', upload.single('file'), async (req, res, next) => {

     // csv file has two columns named Name, Email, I would like to receive value from those..
    
      const data = req.file;
      try {
        if(req.body.file){
          var name = req.file.Name;
          var email = req.file.Email;
        }
        var nomineeData = {userName: name, userEmail: email};
        res.status(200).send(nomineeData);
      } catch (e) {
        res.status(500).json({ fail: e.message });
      }
    });

manageNominee.js

import React, { useRef, useEffect, useState } from "react";
import Axios from "axios";


const ManageNominees = () => {
    const [uploadFile, setUploadFile] = React.useState();
    const [csvData, setCsvData] = useState([]);


    const onChangeCsv = (e) => {
        setCsvData(e.target.files[0]);
    }

    const submitForm = (data) => {
        const dataArray = new FormData();
        dataArray.append("uploadFile", data);
        Axios.put("http://localhost:8000/service/managenominees", dataArray, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then((response) => {
        // successfully uploaded response
      })
      .catch((error) => {
        // error response
      });

    };


    return (
        <div>
            <form onSubmit={submitForm} encType="multipart/form-data">
                <h1>Upload Data</h1>
                <input type="file" name="csvfile" onChange={onChangeCsv}/>
                <button>Submit</button>
            </form>
        </div>
    )
}

export default ManageNominees

【问题讨论】:

  • 在 server.js 中,当你执行 console.log(req.file) 你得到什么输出。
  • 我可以看到 req.body.file 未定义,但我可以看到 req.body object object
  • @Bharath 我可以看到 req.body.file 未定义,我正在获取 req.body 对象对象
  • 你在后端使用 multer 吗?
  • @Bharath 是的,我在后端使用 multer

标签: reactjs express axios react-hooks


【解决方案1】:

有两个问题:

  1. HTML 属性和 mutler 上传选项不同。
  2. 无法直接访问文件值,要么转换缓冲区并读取内容,要么读取文件(下面的代码读取文件)。
const multer  = require('multer');
const bodyParser = require("body-parser");
const path = require('path');

const csv = require('csv-parser');
const fs = require('fs');

...

app.put('/service/managenominees', upload.single('csvfile'), (req, res, next) => {
    console.log(req.file);
    fs.createReadStream(req.file.path)
        .pipe(csv())
        .on('data', (data) => results.push(data))
        .on('end', () => {
            console.log(results);
            // Result would be array as its CSV, iterate over the array and to get username and email id.
            res.status(200).send(results);
        });
});

注意:如果文件不存在,代码不会处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 2014-04-09
    • 1970-01-01
    • 2020-06-13
    相关资源
    最近更新 更多