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.
If you want to do file related validation, i.e mime type or file size, you can do this with fileFilter.
The only problem with the above method is that you cannot do validations against the body of the request.
req.body
is empty inside thefileFilter
callback as explained in this Github issue.There is a workaround for this, which is described in this Github issue. This is not an optimal solution IMO because it forces the client to ensure validation.
Another option is to let the file be saved and then do your validation checks on
req.body
, if the request is invalid you can use something like del or rimraf to delete the persisted file from disk.Another way of addressing this problem.
There is a further discussion about this issue on following link. https://github.com/expressjs/multer/issues/114
This is now possible in 1.0.0.
If you want to abort the upload:
If you want to skip any files that is not pdf: