使用Multer接收文件后转发至其他端点时req.file为undefined
文件转发后Multer获取req.file为undefined的解决方法
问题根源
你的代码存在两个关键错误,导致目标端点无法解析上传的文件:
- FormData.append参数格式错误:文件的元信息(如filename)被错误地写在括号外,变成了无效的逗号表达式,后端无法识别文件的基本属性。
- 手动设置Content-Type导致boundary丢失:multipart/form-data请求需要boundary分隔符来区分字段,手动设置
"Content-Type": "multipart/form-data"会覆盖FormData自动生成的带boundary的请求头,Multer因此无法解析文件。
修复代码
修正转发端代码
const body = new FormData(); // 正确传递文件元信息:将filename等作为append的第三个参数传入 body.append('file', Readable.from(req.files[i].buffer), { filename: req.files[i].originalname, contentType: req.files[i].mimetype }); // 移除手动设置的Content-Type,让Axios自动从FormData生成正确请求头 const response = await axios.post("http://localhost:8080/api/image/images/create", body);
目标端点代码无需修改
你的Multer配置是正确的,保持原代码即可:
const multer = require('multer') const upload = multer({ dest: 'uploads/' }) imageRouter.post('/images/create', upload.single("file"), imageController.postImage);
补充说明
- 使用FormData作为Axios请求体时,Axios会自动生成包含boundary的
Content-Type头,手动设置反而会破坏解析逻辑。 - 若需传递其他字段,直接通过
body.append('字段名', 值)添加即可,无需额外处理请求头。
内容的提问来源于stack exchange,提问作者Karim
相关产品推荐
相关产品推荐

