title: File validation using Multer - Expressjs
body: <p>I have a form which have multiple fields one of them is file field for uploading image.</p>
  
  <pre><code>name = 'john doe'
  location = 'Some location'
  image = (binary)
  </code></pre>
  
  <p>My question is how do I validate this image file for both the times i.e CREATE AND UPDATE.</p>
  
  <p>For create, every field is mandatory but for edit, user might not want to update image but only text fields hence he won't select an image file </p>
  
  <pre><code>router.post('/user', upload.single('image'), userRoute);
  </code></pre>
  
  <p>I have made a middleware like this but this does not give proper validation result. Let's assume that user has selected an image and pressed the submit button then I will get the like this in req.file.</p>
  
  <pre><code>{ fieldname: 'image',
    originalname: 'images (2).jpg',
    encoding: '7bit',
    mimetype: 'image/jpeg',
    destination: 'uploads/top-level',
    filename: 'images (2)-1583345397445.jpg',
    path: 'uploads\\top-level\\images (2)-1583345397445.jpg',
    size: 33766 }
  
  </code></pre>
  
  <p>which make sense but suppose user selected some zip file which is not a file type which I want user to submit hence I have to catch it and show it to user that the file type is not an image. Let me know if i can do using above mentioned middleware.</p>
  
  <pre><code>router.post('/user', userRoute);
  </code></pre>
  
  <p>and i userRoute function I wrote something like this to catch the error</p>
  
  <pre><code>upload(req, res, function (err) {
      if (err instanceof multer.MulterError) {
         // catch error and show to user
      } else if (err) {
         // catch error and show to user here also
      }
      // Logic goes here
  
      // and we get the req.body here 
    })
  </code></pre>
  
  <p>this is good enough for create where every field is mandatory</p>
  
  <p>But for edit how can I save data to database if user is not updating image which means I am getting only two fields </p>
  
  <ol>
  <li>name</li>
  <li>location</li>
  </ol>
  
  <p>If user is selecting image then I will save otherwise i will skip image and save only two fields. HOW can i achieve this and if user is not selecting correct image type then i will have to show error to user.</p>
  
  <p>here is the multer code</p>
  
  <pre><code>var upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) =&gt; {
          cb(null, 'uploads/top-level')
        },
        filename: function (req, file, cb) {
          cb(null, file.originalname.split('.')[0] + '-' + Date.now() + path.extname(file.originalname))
        }
    }),
    fileFilter: (req, file, cb) =&gt; {
      if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
        cb(null, true);
      } else {
        return cb(null, false);
      }
    }
  });
  </code></pre>