node使用formidable上传文件报错
一直报错
bad content-type header, no content-type
const express = require('express');
const fs = require('fs');
const formidable = require('formidable');
const xlsx = require('node-xlsx');
const router = express.Router();
router.post('/', (req, res) => {
console.log(' ########## POST /upload ####### ');
let fileTypeError = false;
const targetPath = `${__dirname}/upload`;
const form = new formidable.IncomingForm();
form.encoding = 'utf-8';
form.keepExtensions = true;
form.maxFieldsSize = 10 * 1024 * 1024;
form.uploadDir = targetPath;
const fields = [];
const files = [];
form.on('field', (field, value) => {
fields.push([field, value]);
});
form.on('file', (field, file) => {
console.log(`upload file: ${file.name}`);
// 判断文件类型是否是xlsx
if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
fileTypeError = true;
}
files.push([field, file]);
});
form.on('end', () => {
// 遍历上传文件
let fileName = '';
let obj = '';
const folderExists = fs.existsSync(targetPath);
if (folderExists) {
const dirList = fs.readdirSync(targetPath);
dirList.forEach((item) => {
if (!fs.statSync(`${targetPath}/${item}`).isDirectory()) {
console.log(`parse item:${targetPath}/${item}`);
fileName = `${targetPath}/${item}`;
if (!fileTypeError) {
// 解析excel
obj = xlsx.parse(fileName);
console.log(JSON.stringify(obj));
// insert into DB
// todo
res.send({ rtnCode: '0', rtnInfo: '成功导入数据' });
} else {
res.send({ rtnCode: '1', rtnInfo: '文件格式不正确' });
}
// delete file
fs.unlinkSync(fileName);
}
});
} else {
res.send({ rtnCode: '1', rtnInfo: '系统错误' });
}
});
form.on('error', (err) => {
res.send({ rtnCode: '1', rtnInfo: '上传出错' });
});
form.on('aborted', () => {
res.send({ rtnCode: '1', rtnInfo: '放弃上传' });
});
form.parse(req);
});
module.exports = router;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决了,postman 应该用form-data而不是binary
http://www.cnblogs.com/shimh/...