0
votes

I have a CRUD app built with node.js, express, and mongoose. In this app I have a form, and 1 of the inputs is a file input to upload an image. I'm using cloudinary, cloudinary storage, and multer to handle these images. If a user uploads an image, I am able to successfully add it to my database and subsequently render it later on. What I haven't been able to figure out is how to set a default image if none is chosen in the file input. Here is my form post on submit:

router.post('/add', parser.single("image"), (req, res) => {
    const newContent = {
        name: req.body.contentName,
        userId: req.user.id,
        username: req.user.username,
        image: {
            url: req.file.url,
            id: req.file.public_id
        },
    }
    new Content(newContent)
    .save()
    .then(() => {
        req.flash('success_msg', 'Content added');
        res.redirect('/content')
    })
});

And here is my cloudinary config:

cloudinary.config({
    cloud_name: ******,
    api_key: ******,
    api_secret: ******
    });
    const storage = cloudinaryStorage({
    cloudinary: cloudinary,
    folder: "demo",
    allowedFormats: ["jpg", "png"],
    transformation: [{ width: 348, height: 236.81, crop: "limit" }]
    });
    const parser = multer({ storage: storage });

I've looked through cloudinary documentation and found a few instances of "default_image" paramater to add, but no matter where I add it in the cloudinary config, I receive error "cannot read property 'url' of undefined. Should this be handled in my post, in my config, or both? For reference, my Content model has the image property set as follows:

        image: {
            url: {
                type: String,
                required: false
            },
            id: {
                type: String,
                required: false
            }
        },

Any help appreciated, thanks!

1

1 Answers

0
votes

When accessing the image you can try :

cloudinary.url("sample.jpg", {width: 300, height: 100, crop: "scale",default_image: "avatar.png"});