stop the file upload in multer if the user validat

2019-07-11 09:05发布

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.

3条回答
爷的心禁止访问
2楼-- · 2019-07-11 09:33

If you want to do file related validation, i.e mime type or file size, you can do this with fileFilter.

multer({
    fileFilter: function(req, file, cb) {
       // file validation...
    }
});

The only problem with the above method is that you cannot do validations against the body of the request. req.body is empty inside the fileFilter 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.

查看更多
聊天终结者
3楼-- · 2019-07-11 09:41

Another way of addressing this problem.

const path = require('path');
multer({
  fileFilter: function (req, file, cb) {

var filetypes = /jpeg|jpg/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());

if (mimetype && extname) {
  return cb(null, true);
}
cb("Error: File upload only supports the following filetypes - " + filetypes);
}

});

There is a further discussion about this issue on following link. https://github.com/expressjs/multer/issues/114

查看更多
倾城 Initia
4楼-- · 2019-07-11 09:46

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)
      }
 })
查看更多
登录 后发表回答