今天上传多文件时报了个错MulterError: Unexpected field
这里代码反复检查没有出错
const express = require('express');
const router = express.Router();
const path = require('path');
/**
文件接收器
**/
const multer = require('multer');
const { log } = require('console');
// 生成仓库信息
const storage = multer.diskStorage({
// 设定存储路径
destination:function(req,file,cb){
// req本次请求信息
// file本次请求的文件
// cb回调函数,利用回调函数来设定存储路径
cb(null,'./uploads')
// 第一个参数null,表示不要修改二进制流文件
},
// 设定文件名称
filename:function(req,file,cb){
// 拿到文件名
const tmp = path.extname(file.originalname);
// 根据文件时间、随机数、后缀名生成新的文件名
const date = `${new Date().getTime()}`;
const random = `${Math.random().toString().slice(2)}`;
const file_name = `avatar_${date}-${random}${tmp}`;
// cb回调函数,利用回调函数来设定文件名称
cb(null,file_name);
}
});
const fileUpload = multer({storage});
/*
暴露
*/
router.post('/upload',fileUpload.array('photo',3),(req,res)=>{
try{
console.log(123);
}catch(e){
console.log(e);
}
});
module.exports = router;
报错信息
MulterError: Unexpected field
at wrappedFileFilter (D:\nodeJsProject\test\node_modules\multer\index.js:40:19)
at Multipart.<anonymous> (D:\nodeJsProject\test\node_modules\multer\lib\make-middleware.js:107:7)
at Multipart.emit (node:events:527:28)
at HeaderParser.cb (D:\nodeJsProject\test\node_modules\busboy\lib\types\multipart.js:358:14)
at HeaderParser.push (D:\nodeJsProject\test\node_modules\busboy\lib\types\multipart.js:162:20)
at SBMH.ssCb [as _cb] (D:\nodeJsProject\test\node_modules\busboy\lib\types\multipart.js:394:37)
at feed (D:\nodeJsProject\test\node_modules\streamsearch\lib\sbmh.js:248:10)
at SBMH.push (D:\nodeJsProject\test\node_modules\streamsearch\lib\sbmh.js:104:16)
at Multipart._write (D:\nodeJsProject\test\node_modules\busboy\lib\types\multipart.js:567:19)
at writeOrBuffer (node:internal/streams/writable:389:12)
最后发现问题是下面这个表单代码from少了闭合标签
<div class="center">单文件上传</div>
<div class="center">
<form action="http://localhost:8888/file/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="avatar">
<button>单文件上传</button>
</div>
<br><br><br>
<div class="center">多文件上传</div>
<div class="center">
<form action="http://localhost:8888/multiple/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="photo" multiple="multiple">
<button>多文件上传</button>
</div>
改正为
<div class="center">单文件上传</div>
<div class="center">
<form action="http://localhost:8888/file/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="avatar">
<button>单文件上传</button>
</form>
</div>
<br><br><br>
<div class="center">多文件上传</div>
<div class="center">
<form action="http://localhost:8888/multiple/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="photo" multiple="multiple">
<button>多文件上传</button>
</form>
</div>
问题解决