0

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 ()

Madhumitha
  • 340
  • 5
  • 24
  • This question smells like a duplicate of https://stackoverflow.com/questions/23114374/file-uploading-with-express-4-0-req-files-undefined, try if the answer there helps you. – Ida Mar 06 '19 at 07:24

1 Answers1

1

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 
    ...
    ...
    ...

});
Nithya Rajan
  • 4,722
  • 19
  • 30
  • Thanks for your code its working fine can you please explain this line `if(req.files != null && typeof req.files == 'object')` – Madhumitha Mar 06 '19 at 07:23
  • `req.files` is an object, you should check whether the `req.files` is available using` req.files != null` and then you should check the type of the `req.files` whether it is object or not using the `typeof` operator. If the answer solves your problem mark it as solved. – Nithya Rajan Mar 06 '19 at 07:32