使用Multer和Express将多个图像上传到Cloudinary

时间:2020-09-07 00:01:24

标签: node.js express backend multer cloudinary

我有这个明确的后端,可以将产品添加到数据库中,现在我已经对其进行了配置,以获取产品图像,然后输入名称,价格,类型和颜色,并且到目前为止效果很好。但是现在我正在尝试使其不能拍摄一张图像,而是最多拍摄四张图像,但是我一直遇到问题。单个图片的初始代码如下

首先配置Cloudinary

const express = require("express");
const cloudinary = require("cloudinary").v2;
const { CloudinaryStorage } = require("multer-storage-cloudinary");
const multer = require("multer");
const verify = require("../routes/verifyToken");


cloudinary.config({
    cloud_name: process.env.CLOUD_NAME,
    api_key: process.env.API_KEY,
    api_secret: process.env.API_SECRET,
});

const storage = new CloudinaryStorage({
    cloudinary: cloudinary,
    params: {
        folder: "Shoes",
        format: async (req, file) => {
            "jpg", "png";
        }, // supports promises as well
        public_id: (req, file) => {
            console.log(
                new Date().toISOString().replace(/:/g, "-") + file.originalname
            );
            return (
                new Date().toISOString().replace(/:/g, "-") + file.originalname
            );
        },
    },
});

const parser = multer({ storage: storage });

然后,发布请求以发布鞋子(产品)。

router.post("/post/menshoe", verify,parser.single("shoeImage"), async (req, res) => {
                // console.log(req.file);

                if (!req.file) return res.send("Please upload a file");

                // console.log(req.file); // to see what is returned to you
                const image = {};

                console.log(req.file)

                const shoeUpload = new MenShoe({
                    shoeImage: req.file.path,
                    name: req.body.name,
                    type: req.body.type,
                    price: req.body.price,
                    color: req.body.color,
                });

                console.log(shoeUpload);

                try {
                    const shoe = await shoeUpload.save();
                    res.json({ msg: "Shoe uploaded", success: true, shoe });
                } catch (err) {
                    console.log(err);
                    res.json({
                        msg: "Failed to upload",
                        success: false,
                        err,
                    });
                }
        }
);

我想指出的是,我已经尝试过研究一种方法,但是遇到的每个答案都使用一种完全不同的方法来发布图像,因此我认真地尝试避免从头开始编写该图像。已经写了很多完全像这样的代码。如果有人可以通过对该代码的一些调整来帮助我实现这一目标,我将非常感激。

预先感谢

1 个答案:

答案 0 :(得分:0)

在模型目录中;

const shoeSchema = new mongoose.Schema({
    // other properties here
    shoeImage: [{
        type: String,
        required: true // it could be optional
    }],
});
module.exports = Shoe = mongoose.model('product', shoeSchema);

在您的发布路线内,

router.post("/post/menshoe", verify,parser.array("shoeImage", 4), async 
    (req, res) => {
    const { name, type, price, color } = req.body;
    try {
        let shoeUpload = new MenShoe({
            name,
            type,
            price,
            color
        });
    
        if (req.files) { // if you are adding multiple files at a go
            const imageURIs = []; // array to hold the image urls
            const files = req.files; // array of images
            for (const file of files) {
                const { path } = file;
                imageURIs.push(path);
            };

            shoeUpload['shoeImage'] = imageURIs; // add the urls to object

            await shoeUpload.save();
            return res.status(201).json({ shoeUpload });
            
            }

            if (req.file && req.file.path) {// if only one image uploaded
                shoeUpload['shoeImage'] = req.file.path; // add the single  
                await shoeUpload.save();
                return res.status(201).json({ shoeUpload });
            };

            // you could save here without the image
            ...

            return res.status(400).json({ // in case things don't work out
                msg: 'Please upload an image'
            });
    }catch {
        console.error("server error occur", error.message);//only in dev
        return res.status(500).send("Server Error Occurred");
    }
});