问题描述
我试图通过前端和 node.js 服务器上的 react 上传一个csv文件,并将其存储在一个数组中。我已经使用 fast csv 模块来解析此csv文件,但是 fast csv 模块正在请求缓冲区或url。我的反应是给我发了一个空白的对象。我被严重卡住?,请帮助我。我指望你。
import React from 'react';
import axios from 'axios';
const [company,setCompany] = React.useState('');
const [city,setcity] = React.useState("");
const [file,setFile] = React.useState("");
const [open,setOpen] = React.useState(false);
let csvData = new FormData();
csvData.append("file",file);
const handleSubmit = async () => {
try {
const res = await axios.post('http://localhost:5000/csv',{ csvData } );
console.log(res);
} catch (error) {
console.error(error);
}
};
<input className={classes.input} id="contained-button-file" multiple type="file"
onChange={(e) => setFile(e.target.files[0])} />
<label htmlFor="contained-button-file">
<Button variant="contained" color="primary"
component="span" startIcon={<CloudUpload />}>
Upload Data
</Button>
</label>
更新:
从提供的响应中更新了后端代码,以便现在就可以获得前端代码的帮助。
更新代码后,后端出现错误。
错误:TypeError: Cannot read property 'path' of undefined
我的后端代码是这样的:
import fs from 'fs';
import multer from 'multer';
const upload = multer({ dest: '/tmp/csv/' });
const csv = require('fast-csv');
router.post('/csv',upload.single('file'),(req,res,next) => {
let filerows = [];
let stream = fs.createReadStream(req.file.path);
stream.pipe(
// csv.fromPath(req.file.path)
csv
.parse()
.on('data',(data) => {
filerows.push(data);
})
.on('error',() => {
res.status(500).json({ message: 'Failed to upload' });
})
.on('end',() => {
// console.log(filerows);
const sql =
'INSERT INTO bikes_database(website,company_name,category,city,brand_name,bike_name,bike_url,hour_rent,weekday_rent,weekend_rent,7_days_rent,15_days_rent,30_days_rent,gst,convinence_fee,booking_confirmation,helmet,deposit,km_limit,speed_limit,home_delivery,product_page) VALUES ?';
db.query(sql,[filerows],(err,result) => {
if (err) throw err;
res.json("uploaded successfully")
});
fs.unlinkSync(req.file.path);
})
);
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)