如何使用Node.js在单个路由中同时上传图片与视频至S3
解决Multer多字段文件上传的Unexpected Field错误
问题背景
原本视频(files字段)和图片(photos字段)的上传在独立路由中均可正常运行,但尝试合并为单个路由并使用upload.array(["photos","files"],10)时,出现MulterError: Unexpected field错误。
错误原因
Multer的array()方法仅支持单个字段名,用于处理该字段下的多个文件;若需同时接收多个不同字段的文件,必须使用fields()方法,而非array()。
解决方案
1. 替换路由中的Multer中间件
将原来的upload.array()替换为upload.fields(),传入包含各字段配置的数组:
router.post('/upload', upload.fields([ { name: 'photos', maxCount: 10 }, { name: 'files', maxCount: 5 } ]), async (req, res) => { // 处理逻辑 });
2. 调整文件处理逻辑
使用fields()后,req.files不再是单一数组,而是一个对象,键为字段名,值为对应字段的文件数组。修改后的完整路由代码如下:
router.post('/upload', upload.fields([ { name: 'photos', maxCount: 10 }, { name: 'files', maxCount: 5 } ]), async (req, res) => { try { // 处理图片 const product = new Product(); if (req.files.photos) { product.photos.push(...req.files.photos.map(file => file.location)); await product.save(); } // 处理视频 const video = new Video(); video.url = []; if (req.files.files) { req.files.files.forEach(file => { video.url.push(file.location); }); const savedVideo = await video.save(); } res.json({ message: '文件上传成功', product: product, video: savedVideo || null }); } catch (error) { res.status(500).json({ message: '上传失败', error: error.message }); } });
3. 中间件无需修改
你的Multer-S3中间件配置保持原样即可,它能同时处理不同字段的文件上传。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

