【问题标题】:Uploading Multiple Images to Cloudinary Using Multer and Express使用 Multer 和 Express 将多个图像上传到 Cloudinary
【发布时间】:2020-12-25 10:10:41
【问题描述】:

我有这个用于将产品添加到数据库的快速后端,现在我已经将它配置为获取产品图像,然后是名称、价格、类型和颜色,到目前为止它运行良好。但现在我正在努力让它不能拍摄一张图像,而是最多四张,但我一直遇到问题。单张图片的初始代码如下

首先是 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,
                    });
                }
        }
);

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

提前致谢

【问题讨论】:

  • 你必须描述你面临什么样的问题。你的问题太宽泛了
  • @iwaduarte 我只想了解如何使用上面的代码在单个请求中上传多个图像。这就是我不知道如何使用上面的代码来做的事情
  • router.post("/post/menshoe", verify,parser.single("shoeImage"), async (req, res) => { 改成这个 "router.post("/ post/menshoe", verify,parser.array("shoeImage"), async (req, res) => {", 检查是否可以上传多张图片
  • @JatinMehrotra 我实际上在研究时看到了类似的东西,我已经尝试过了。它像这样 ``` router.post("/post/menshoe", verify,parser.array("shoeImage, 4"), async (req, res) => {``` 但它仍然没有工作
  • 应该是这样的 ``` router.post("/post/menshoe", verify,parser.array("shoeImage," 4), async (req, res) => { ``, 检查引号的位置 -> " shoeimage 必须在引号中而不是 4

标签: node.js express backend multer cloudinary


【解决方案1】:

在您的模型目录中;

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");
    }
});

【讨论】:

  • 这拯救了我的一天
猜你喜欢
  • 2019-02-21
  • 1970-01-01
  • 2018-07-17
  • 2017-05-22
  • 1970-01-01
  • 2021-04-04
  • 2020-04-07
  • 2016-09-25
  • 2021-01-24
相关资源
最近更新 更多