You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何组合Multer的single与array两种上传方式?

如何同时处理单张图片和图片数组的上传?

你需要实现单张可选图片(frontImage)和可选图片数组(files[])的上传功能,且二者需区分开。单独使用upload.single('frontImage')或upload.array('files[]')时代码能正常运行,现在要组合这两种上传方式,正确的做法是使用multer的upload.fields()方法,它支持同时处理多个不同类型的文件字段。

修改后的代码示例:

router.post(
  '/create',
  upload.fields([
    { name: 'frontImage', maxCount: 1 }, // 单张图片,maxCount设为1限制数量
    { name: 'files[]', maxCount: 10 }    // 图片数组,maxCount可根据需求调整最大上传数
  ]),
  [check('title').not().isEmpty()],
  flashCardsControllers.createFlashCard
);

在控制器中获取文件:

  • 单张图片frontImage:通过req.files.frontImage[0]获取(fields方法返回的所有文件都是数组格式,即使是单文件)
  • 图片数组files[]:通过req.files['files[]']获取,这是一个包含所有上传图片的数组

注意:前端提交表单时必须设置enctype="multipart/form-data",否则文件无法正常上传。

内容的提问来源于stack exchange,提问作者dawphin777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 14:17:34