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

如何配置后端Schema以接收FormData传递的文件对象数组?

如何配置MongoDB Schema接收FormData传递的文件数组

前端实现

FormData数组文件处理

const noteSubmitHandler = async event => {
  event.preventDefault();
  try {
    const formData = new FormData();

    for (let i = 0; i < attachments.length; i++) {
      formData.append('files[]', attachments[i]);
    }
    formData.append('title', title);

    await sendRequest(
      process.env.REACT_APP_BACKEND_URL + '/notes/create',
      'POST',
      formData,
      { Authorization: 'Bearer ' + auth.token }
    );
    navigate(`/${auth.userId}/notes`);
  } catch (err) { }
};

文件输入框

<input
  type="file"
  accept=".jpg,.png,.jpeg"
  multiple
  onChange={(e) => setAttachments([...e.target.files])}
/>

注意:e.target.files是FileList对象,需要转成数组再存入状态,否则循环时可能出现异常。

后端Schema配置问题

前端执行console.log(formData.getAll('files[]'))能得到预期的文件数组,但后端尝试以下两种Schema都无法正确接收:

方案一

const noteSchema = new Schema({
  title: { type: String, required: true },
  "files[]": [{ type: Object }],
});

方案二

const noteSchema = new Schema({
  title: { type: String, required: true },
  files: [{ type: Object }],
});

正确解决方案

1. 后端Schema定义

直接用files字段,同时明确文件元信息的存储结构(MongoDB不适合存原始文件对象,通常存储文件的路径、文件名等信息):

const noteSchema = new Schema({
  title: { type: String, required: true },
  files: [{
    filename: { type: String, required: true }, // 文件名
    path: { type: String, required: true }, // 文件存储路径
    mimetype: { type: String, required: true }, // 文件类型
    size: { type: Number, required: true } // 文件大小
  }]
});

2. 后端文件上传处理

需要用multer中间件解析FormData中的文件:

  • 先配置multer的本地存储规则:
const multer = require('multer');
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 自定义文件存储目录
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname); // 生成唯一文件名避免冲突
  }
});
const upload = multer({ storage: storage });
  • 在路由中使用multer接收多文件:
router.post('/notes/create', upload.array('files[]'), async (req, res) => {
  // req.files是multer解析后的文件数组,包含文件名、路径等元信息
  const note = new Note({
    title: req.body.title,
    files: req.files.map(file => ({
      filename: file.filename,
      path: file.path,
      mimetype: file.mimetype,
      size: file.size
    }))
  });
  await note.save();
  res.status(201).json({ message: 'Note created' });
});

关键说明

  • 前端用files[]作为FormData的键,multer会自动将其解析为req.files数组,不需要在Schema中写"files[]"。
  • 不能直接将原始文件对象存入MongoDB,必须提取文件的元信息存储,实际文件可存在本地目录或云存储服务中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:17:09