【问题标题】:Multer - how to handle files using upload.fields() once files have been submittedMulter - 提交文件后如何使用 upload.fields() 处理文件
【发布时间】:2020-09-10 18:18:03
【问题描述】:

我一直在尝试使用 Multer,并且正在使用 Mongoose 将电影文档保存到 MongoDB。在让用户在一个输入字段中提交图像并在单独的输入字段中提交视频后,我使用 multer 的 upload.fields() 选项来处理这些文件。

我希望 posterImageName 保存“myImage”的文件名,而 trailVideoName 保存“myVideo”的文件名,以便在从数据库中获取图像和视频时显示。当我尝试在我的电影文档中设置这些文件名并尝试将其保存到我的数据库时,我收到以下错误:“无法读取未定义的属性‘文件名’”

这是我的代码:

const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './public/uploads/')
        },

        filename: (req, file, cb) => {
            cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
        },
    }),

    limits: {fileSize: 10000000000},
    fileFilter: (req, file, cb) => {
        // Allowed ext
        const filetypes = /jpeg|jpg|png|gif|mp4/;
        // Check ext
        const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
        // Check mimetype
        const mimetype = filetypes.test(file.mimetype);

        if (mimetype && extname) {
            return cb(null, true);
        } else {
            cb('Error: Images and Videos Only')
        }

    }
})

router.post('/movies', upload.fields([{name: 'myImage'}, {name: 'myVideo'}]), (req, res) => {
    const movie = new Movie({
        title: req.body.title,
        posterImageName: req.files[0].filename,
        trailerVideoName: req.files[1].filename
    })

    movie.save((error, movie) => {
        if (error) return console.error(error);
        console.log(`${movie.title} saved to movies collection`);
    });
})

我曾尝试寻找关于如何使用upload.fields() 的良好解释,但找不到任何解释,因为我看到的所有教程和论坛都在谈论upload.single() 或upload.array()。如果您需要其他代码,请告诉我。非常感谢所有帮助:)

【问题讨论】:

    标签: node.js mongodb express multer


    【解决方案1】:

    在multer的README.md文档中有提到

      // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
      //
      // e.g.
      //  req.files['avatar'][0] -> File
      //  req.files['gallery'] -> Array
      //
      // req.body will contain the text fields, if there were any
    

    字段的名字基本上对应req.files的key

        const movie = new Movie({
            title: req.body.title,
            posterImageName: req.files['myImage'][0].filename,
            trailerVideoName: req.files['myVideo'][0].filename
        })
    

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 2020-09-08
      • 2018-01-28
      • 2021-11-02
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      相关资源
      最近更新 更多