前端代码
<form action="http://192.168.1.81:3001/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file" >
<input type="file" name="file" >
<input type="file" name="headImg" >
<input type="file" name="headImg" multiple="multiple">
<input type="submit" value="提交">
</form>
express代码
var multiparty = require('multiparty');
var path = require('path');
router.post('/upload', (req, res) => {
console.log('upload-req.headers---', req.headers)
try {
var form = new multiparty.Form({
encoding: 'utf8',
uploadDir: path.join(__dirname, '../public/temp/')
});
form.parse(req, function(err, fields, files) {
let flod = path.join(__dirname, '../public/upload-img/')
let fileName = files.file[0].originalFilename
fs.writeFile(flod + fileName, fs.readFileSync(files.file[0].path), (err, result) => {
if (err) {
console.error('接受图片错误', err)
return
}
})
});
res.redirect('http://192.168.1.81:3001/test')
} catch (error) {
res.end('err')
}
})
form.parse里的files对象
let obj = {
file: [
{ fieldName: 'file',
originalFilename: 'WechatIMG148.jpeg',
path: '/Users/mee/code/node/uploadfile/public/temp/Xv1zVJ9vL12JRvavo61UJWHe.jpeg',
headers: [Object],
size: 69760
},
{ fieldName: 'file',
originalFilename: 'WechatIMG149.jpeg',
path: '/Users/mee/code/node/uploadfile/public/temp/HrPO8gnJL5YAed0ZKuQpirJ5.jpeg',
headers: [Object],
size: 71986
}
],
headImg: [
{ fieldName: 'headImg',
originalFilename: 'sky.jpeg',
path: '/Users/mee/code/node/uploadfile/public/temp/ZipFJERFf0H5z0Tbt-Kzdi4b.jpeg',
headers: [Object],
size: 151759
},
{ fieldName: 'headImg',
originalFilename: 'star.png',
path: '/Users/mee/code/node/uploadfile/public/temp/BjCV1NX7jnlAPtGHJ1bZb8W7.png',
headers: [Object],
size: 749672
},
{ fieldName: 'headImg',
originalFilename: 'pic.png',
path: '/Users/mee/code/node/uploadfile/public/temp/-H8rJBkRrm7eUNuwSSDd3I9n.png',
headers: [Object],
size: 749672
}
]
}
headers = {
'content-disposition': 'form-data; name="headImg"; filename="108.png"',
'content-type': 'image/png'
}