0

I am able to upload images but if i need to edit my page where sometimes I need not upload a newer image, how do I proceed?

I am checking using the below code but every time its giving me "undefined".

    router.post('/update/:id', function(req, res, next) {

    var Storage = multer.diskStorage({
        destination: function (req, file, callback) {
            callback(null, "./uploads/images");
        },
        filename: function (request, file, callback) {
            callback(null, file.originalname);
        }
      });

    upload(req, res, function (err) {
      if (typeof req.files.image !== "undefined") {
        // code
      } else if (typeof req.files.image === "undefined") {
        // code
      }

    home.update(req.files[0].path, req.body.input_field_name, req.params.id);
      req.flash('edit', 'Updated.');
      res.redirect('edit/' + req.params.id);
    });

    });

Any help?

Solution

upload(req, res, function (err) {
  if (typeof req.files !== 'undefined' && req.files.length > 0) {
      //code
  } else {
      //code
  }
});
  • Could you provide some more context? – Hartger Oct 20 '17 at 08:34
  • @Hartger I have included the full code. Please check. Basically, I want to check if I am uploading any image or not. In both the cases, the code must work. –  Oct 20 '17 at 09:10
  • what does console.log(req.files) output for you? Perhaps checking on the length of req.files would work. Are you using bodyparser btw? – Hartger Oct 20 '17 at 09:18
  • @Hartger console.log(req.files) gives me "undefined". Yes, I am using "bodyparser". –  Oct 20 '17 at 09:22
  • Appearantly bodyparser no longer supports file uploads. See: https://stackoverflow.com/questions/23114374/file-uploading-with-express-4-0-req-files-undefined – Hartger Oct 20 '17 at 09:25
  • @Hartger But I am able to upload. The problem is I need to validate whether I am uploading a file or not. As I am using multer, is there anyway to validate using multer? –  Oct 20 '17 at 09:31
  • Shouldn't req.files be req.file? – Hartger Oct 20 '17 at 10:00
  • @Hartger req.files and req.file, both are showing "undefined". –  Oct 20 '17 at 10:04
  • When you define upload, do you define it as multer().single(fieldName)? – Hartger Oct 20 '17 at 12:54
  • @Hartger i am defining upload as: var upload = multer({ storage: Storage }).array("image", 1); –  Oct 23 '17 at 04:09

1 Answers1

1
   if (typeof req.query.image !== "undefined") {
        // code
        console.log("File is uploaded");
      } else if (typeof req.query.image === "undefined") {
        // code
        console.log("File is not uploaded");
      }

//if you are using post then use - req.body.image