无法使multer filefilter错误处理工作

Mer*_*erk 8 node.js express multer

我在node.js/multer中玩文件上传

我得到了存储并限制了工作.但是现在我正在使用filefilter简单地拒绝mimetype这样的文件,如下所示:

fileFilter: function (req, file, cb) {
 if (file.mimetype !== 'image/png') {
  return cb(null, false, new Error('goes wrong on the mimetype'));
 }
 cb(null, true);
}
Run Code Online (Sandbox Code Playgroud)

当文件上传不是png时,它不会接受它.但它也不会触发if(err)

当文件很大时,它确实会产生错误.所以不知怎的,我需要在filefilter上生成一个错误,但我不确定如何和猜测new Error是错误的

那么如果文件不正确,我该如何生成错误呢?我究竟做错了什么?

完整代码:

var maxSize = 1 * 1000 * 1000;

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, 'public/upload');
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname);
  }
});


var upload = multer({
   storage : storage,
   limits: { fileSize: maxSize },
   fileFilter: function (req, file, cb) {
     if (file.mimetype !== 'image/png') {
       return cb(null, false, new Error('I don\'t have a clue!'));
     }
     cb(null, true);
   }

 }).single('bestand');


router.post('/upload',function(req,res){
    upload(req,res,function(err) {
        if(err) {
              return res.end("some error");
        }
    )}
)}
Run Code Online (Sandbox Code Playgroud)

Krz*_*pka 13

fileFilter函数可以访问请求对象(req).您的路由器中也提供此对象.

因此,在fileFitler中,您可以添加带有验证错误或验证错误列表的属性(您可以上传许多文件,其中一些文件可以通过).在路由器中,检查是否存在有错误的属性.

在过滤器中:

fileFilter: function (req, file, cb) {
 if (file.mimetype !== 'image/png') {
  req.fileValidationError = 'goes wrong on the mimetype';
  return cb(null, false, new Error('goes wrong on the mimetype'));
 }
 cb(null, true);
}
Run Code Online (Sandbox Code Playgroud)

在路由器:

router.post('/upload',function(req,res){
    upload(req,res,function(err) {
        if(req.fileValidationError) {
              return res.end(req.fileValidationError);
        }
    )}
)}
Run Code Online (Sandbox Code Playgroud)

  • 当然。这总是关于你想要什么。有时检查 ext 就足够了,我们不关心它会发生什么。有时您想要检查文件的第一个字节以确定它的实际类型 - 例如当您需要对此文件执行某些操作时。但如果文件损坏怎么办?在这种情况下,您还需要检查完整文件。作为工程师,我们的责任是为每种场景选择最好的工具 (2认同)

小智 6

您可以将错误作为第一个参数传递。

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

    cb(null, true)
  }
})
Run Code Online (Sandbox Code Playgroud)


Ömü*_*giz 5

更改fileFilter并将错误传递给函数cb

function fileFilter(req, file, cb){
   if(file.mimetype !== 'image/png'){
       return cb(new Error('Something went wrong'), false);
    }
    cb(null, true);
};
Run Code Online (Sandbox Code Playgroud)