MulterError: Can not add multiple images

MulterError: Can not add multiple images

我在尝试上传多张图片时遇到此错误

MulterError: Unexpected field
    at wrappedFileFilter (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/multer/index.js:40:19)
    at Busboy.<anonymous> (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/multer/lib/make-middleware.js:114:7)
    at Busboy.emit (events.js:210:5)
    at Busboy.emit (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/busboy/lib/main.js:38:33)
    at PartStream.<anonymous> (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/busboy/lib/types/multipart.js:213:13)
    at PartStream.emit (events.js:210:5)
    at HeaderParser.<anonymous> (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/dicer/lib/Dicer.js:51:16)
    at HeaderParser.emit (events.js:210:5)
    at HeaderParser._finish (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/dicer/lib/HeaderParser.js:68:8)
    at SBMH.<anonymous> (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/dicer/lib/HeaderParser.js:40:12)
    at SBMH.emit (events.js:210:5)
    at SBMH._sbmh_feed (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/streamsearch/lib/sbmh.js:159:14)
    at SBMH.push (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/streamsearch/lib/sbmh.js:56:14)
    at HeaderParser.push (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/dicer/lib/HeaderParser.js:46:19)
    at Dicer._oninfo (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/dicer/lib/Dicer.js:197:25)
    at SBMH.<anonymous> (/Users/theodosiostziomakas/udemy/MERN_COURSE/backend/node_modules/dicer/lib/Dicer.js:127:10)

这是我添加多张图片的代码。

router.put(
    '/gallery-images/:id',
    uploadOptions.array('images', 10),
    async (req, res) => {
        if (!mongoose.isValidObjectId(req.params.id)) {
            return res.status(400).send('Invalid Product Id');
        }
        const files = req.files;
        let imagesPaths = [];
        const basePath = `${req.protocol}://${req.get('host')}/public/uploads/`;
 
        if (files) {
            files.map((file) => {
                imagesPaths.push(`${basePath}${file.filename}`);
            });
        }
 
        const product = await Product.findByIdAndUpdate(
            req.params.id,
            {
                images: imagesPaths,
            },
            { new: true }
        );
 
        if (!product)
            return res.status(500).send('the gallery cannot be updated!');
 
        res.send(product);
    }
);

谢谢, 西奥.

可能是因为您也将 image 作为单个图像发送,所以 Multer 将首先尝试解析该图像,并且不会在 fildName 中找到匹配项,因为您在服务器端 imagesfieldName.