前端调用multer文件上传接口报错:Cannot read properties of undefined (reading 'buffer')
问题:前端调用Multer文件上传接口报错Cannot read properties of undefined (reading 'buffer')
开发项目时需要实现PDF上传功能,后端使用multer库处理文件上传的POST请求。在Postman中测试http://localhost:3000/schedule/upload接口一切正常,但通过前端调用该接口时出现错误:Cannot read properties of undefined (reading 'buffer')。
客户端代码
const saveFile = async () => { let file = document.getElementById("fileInp").files[0]; console.log('inside ' + file) let formdata = new FormData(); formdata.append("schedule", file); const config = { url : '/schedule/upload', method : 'post', data : { filename : 'schedule', formdata }, headers : { Authorization : `Bearer ${token}`, "Content-Type": "multipart/form-data" } } try { const res = await axios(config); console.log(res.data); } catch (e) { console.log(e); } return; }
服务端代码
const upload = multer({ limits : 1000000 }) fileRouter.post("/schedule/upload",auth,upload.single("schedule"),async(req,res)=>{ await File.findOneAndUpdate({fileName : "schedule"},{fileName : req.body.filename, file : req.file.buffer},{upsert : true}).exec(); res.status(200).send("Schedule uploaded"); })
问题原因及修复方案
核心问题
- 请求数据格式错误:将FormData嵌套在普通对象中作为axios的
data值,axios会把对象序列化为JSON格式发送,而非multer期望的multipart/form-data格式,导致后端无法解析到文件,req.file为undefined。 - 手动设置Content-Type导致boundary缺失:
multipart/form-data请求需要自动生成的boundary分隔符区分表单字段,手动设置该请求头后,axios不会自动添加boundary,后端无法正确解析表单数据。
修改后的客户端代码
const saveFile = async () => { let file = document.getElementById("fileInp").files[0]; console.log('inside ' + file); let formdata = new FormData(); formdata.append("schedule", file); formdata.append("filename", "schedule"); // 将filename追加到FormData中 const config = { url: '/schedule/upload', method: 'post', data: formdata, // 直接传入FormData作为请求体 headers: { Authorization: `Bearer ${token}` // 移除手动设置的Content-Type,axios会自动处理 } } try { const res = await axios(config); console.log(res.data); } catch (e) { console.log(e); } return; }
说明
- 直接将FormData作为axios的
data参数,axios会自动识别并设置正确的multipart/form-data请求头及boundary。 - 把
filename字段追加到FormData中,后端就能通过req.body.filename获取到该值。
内容的提问来源于stack exchange,提问作者AMRITESH GUPTA
相关产品推荐
相关产品推荐

