Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop the file upload in multer if the user validation fails

The file uploading is done by multer by using this code, but how to stop the file upload when the user validation fails. where to write the user validation part in this code

router.post('/profilePicture',
 multer({dest: './uploads/',
rename: function (fieldname, filename,req,res) {
      return image = req.body.userId+'-'+dateTime+'-'+randomId();
    },
    onFileUploadStart: function (file,req,res) {
        if(file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
          imageUploadDone = false;
          return false;
        }
        //console.log(file.originalname + ' is starting ...');
    },
    onFileUploadComplete: function (file,req,res) {
      //console.log(file.fieldname + ' uploaded to  ' + file.path);
      if(file.mimetype == 'image/jpg')
        extn  = '.jpg';
      if(file.mimetype == 'image/jpeg')
        extn  = '.jpeg';
      if(file.mimetype == 'image/png')
        extn  = '.png';
      imageUploadDone=true; 
    }
}),function(req, res) { 
      upload(req,res,function(err) {
    if(imageUploadDone==true){
      //console.log(image);
      var userInfo = {'userId':req.body.userId,'newImage':address+image+extn,'path':'./uploads/'};
          db.profilePicture(userInfo,function(result){
            if(result.message == 'image path added'){
              res.json({'success':'1','result':{'message':'Profile Picture Updated','imageUrl':address+image+extn},'error':'No Error'});
            }
          });
    }
    if(imageUploadDone == false){
    res.json({'success':'0','result':{},'error':'file format is not supported'});
  }
  });
});

i try to validate the user on the events like onFileUploadStart and onFileUploadComplete. if user is not valid still the file gets uploaded to the path.

like image 767
Karthik Avatar asked Dec 18 '22 20:12

Karthik


1 Answers

This is now possible in 1.0.0.

If you want to abort the upload:

multer({
      fileFilter: function (req, file, cb) {
         if (path.extname(file.originalname) !== '.pdf') {
                 return cb(new Error('Only pdfs are allowed'))
          }

         cb(null, true)
       }
 })

If you want to skip any files that is not pdf:

multer({
      fileFilter: function (req, file, cb) {
          if (path.extname(file.originalname) !== '.pdf') {
                  return cb(null, false)
       }

      cb(null, true)
      }
 })
like image 167
Skhumbuzo Matine Avatar answered Dec 21 '22 09:12

Skhumbuzo Matine