1

I have this express backend for adding products to a database, now I have configured it to take product image then name, price, type, and color and it has worked very well so far. But now I am trying to make it so that it can take not one image but up to four but I've been running into issues. The initial code for the single image is as follows

First the config for 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 });

Then now the post request to post the shoes(product).

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

I would like to point out that I've tried to research for a way but each answer that I have encountered is using a completely different way to post images and I am seriously trying to avoid starting to write this from scratch as I have written a lot of code exactly like this. I would really appreciate it if anyone can help me achieve this with just a few tweaks to this code.

Thanks in advance

6
  • You have to describe what kind of issues you are facing.Your question is too broad Commented Sep 7, 2020 at 0:20
  • @iwaduarte I just want to find out how to upload multiple images in a single request using the code above. That's what I don't know how to do using the code above Commented Sep 7, 2020 at 1:18
  • 1
    router.post("/post/menshoe", verify,parser.single("shoeImage"), async (req, res) => { change this to this "router.post("/post/menshoe", verify,parser.array("shoeImage"), async (req, res) => {", check if it works for uploading multiple images Commented Sep 7, 2020 at 4:03
  • @JatinMehrotra I actually saw something like this while I was researching and I have tried it. it goes something like this ``` router.post("/post/menshoe", verify,parser.array("shoeImage, 4"), async (req, res) => {``` But it still doesn't work Commented Sep 7, 2020 at 5:19
  • 1
    it should be something like this ``` router.post("/post/menshoe", verify,parser.array("shoeImage," 4), async (req, res) => {``, check the position of quotes -> " shoeimage must be in quotes not 4 Commented Sep 7, 2020 at 5:29

1 Answer 1

4

In your model dir;

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

Inside your post route,

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");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.