react批量上传
一、后端接口(node)
router.post("/excelUpload", (req, res) => {
const form = new multiparty.Form() //multiparty需要导入
form.uploadDir = "upload"
form.parse(req, async (err, formData, excelData) => {
let dataUrl = excelData.file[0].path
let data = xlsx.parse(dataUrl)[0].data //xlsx需要导入
let brr = [] //存放数据的数组
data.forEach(item => {
brr.push({ //这里是相关的字段
"name": item[0],
"depart": item[1],
"starttime": item[2],
"endtime": item[3],
"desclist": item[2]
})
})
brr.forEach(async(item)=>{
await peoplegoModel.create(item) //peopleModel是数据模型,
//create加入数据库中
})
})
})
二、react前端
代码如下(示例):
<Upload {...props}>
<Button icon={<UploadOutlined />}>批量上传</Button>
</Upload>
const props = {
name: 'file',
action: 'http://127.0.0.1:7777/excelUpload',
headers: {
authorization: 'authorization-text',
},
onChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
message.success(`${info.file.name} file uploaded successfully`);
} else if (info.file.status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
},
};
总结
文件上传antd里的代码直接复制,只需要改接口即可,excel里面的数值要和数据库中的字段对应