Madhumitha
Madhumitha

Reputation: 338

Edit page image upload concept using Nodejs

Am new in Nodejs, In my project am trying to upload image in Edit page.

Here am using two conditions, those are following:

  1. If user select image file means
  2. With out selecting

If user select image file new image upload and save it in my database.

else save old_image data without upload file.

This is my code:

router.post('/edit_coupon/:id', verifyToken, function(req, res, next){
    let update_coupon = {};
    var file = req.files.image;
    if(Object.keys(req.files).length != 0) // if user select file
    {
        var random = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;
        const image_name = random+file.name;
        file.mv('public/assets/images/coupons/'+image_name, function(err){
            if (err)
            {
                return res.status(500).send(err);
            }
        });
        update_coupon.image = image_name;
    }
    else
    {
        update_coupon.image = req.body.old_image;  // if user didnot select file
    }

    // code for update 
    ...
    ...
    ...

});

My above code not working when user without select image showing error like

TypeError: Cannot convert undefined or null to object at Function.keys ()

Upvotes: 0

Views: 979

Answers (1)

Nithya Rajan
Nithya Rajan

Reputation: 4884

Check whether the req.files is available and it's a type of object or not using if statement and typeof operator as follows:

router.post('/edit_coupon/:id', verifyToken, function(req, res, next){
    let update_coupon = {};
    var file = req.files.image;
    if(req.files != null && typeof req.files == 'object') {
     if(Object.keys(req.files).length != 0) // if user select file
     {
        var random = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;
        const image_name = random+file.name;
        file.mv('public/assets/images/coupons/'+image_name, function(err){
            if (err)
            {
                return res.status(500).send(err);
            }
        });
        update_coupon.image = image_name;
    }
    else
    {
        update_coupon.image = req.body.old_image;  // if user didnot select file
    }

   }

    // code for update 
    ...
    ...
    ...

});

Upvotes: 1

Related Questions