如何创建一个模式来接受文件对象数组?

问题描述 投票:0回答:1

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)}
/>

如果我

console.log(formData.getAll('files[]'));
我得到了预期的文件数组:

如何在后端设置架构以接受数组?我试过:

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

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

但都不起作用。

javascript reactjs file-upload form-data
1个回答
0
投票

您无法将文件对象从浏览器存储到 Mongodb 中,但您可以提取属性并将其存储为数组。以下是如何构建您的

noteSchema

注意架构:

const mongoose = require('mongoose');

const fileSchema = new mongoose.Schema({
  name: { type: String, required: true },
  data: { type: Buffer, required: true },
  contentType: { type: String, required: true }
});

const noteSchema = new mongoose.Schema({
  title: { type: String, required: true },
  files: [fileSchema] // Embed the file data within the Note schema
});

const Note = mongoose.model('Note', noteSchema);

module.exports = Note;

在此文件模型中,我们存储文件的名称、二进制数据和内容类型。您可以根据您的需求调整 fileSchema 中的字段。

当您在服务器上收到文件时,应将每个文件保存为 Note 模型中的单独文档。您可以使用 Multer 获取文件数组。

创建笔记文件:

const express = require('express');
const multer = require('multer');
const router = express.Router();
const Note = require('../models/note');

const upload = multer({ dest: 'uploads/' });

router.post('/notes/create', upload.array('files'), async (req, res) => {
  try {
    const { title } = req.body;
    const files = req.files;

    // Create a new Note instance with embedded file data
    const newNote = new Note({
      title,
      files: files.map(file => ({
        name: file.originalname,
        data: file.buffer,
        contentType: file.mimetype
      }))
    });

    // Save the Note instance to the database
    const savedNote = await newNote.save();

    res.status(201).json({ note: savedNote });
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: 'Server error' });
  }
});

module.exports = router;
© www.soinside.com 2019 - 2024. All rights reserved.