【问题标题】:How To Handle Error created by upload call in multer when the number of files limit exceeds?当文件数量超过限制时,如何处理multer中的上传调用创建的错误?
【发布时间】:2019-09-05 02:15:34
【问题描述】:

使用我的错误处理,它会按预期抛出错误,即使它上传了一些文件(直到达到限制)然后抛出错误。在上传一些块文件之前如何抛出这个错误?

如果超过上传文件的限制,如何在上传前抛出错误?提前致谢!

我试过了:

app.post('/upload',[
multer({
dest    : function(req, file, cb){
let dest = 'uploads/1992-12-11/'
let len = parseInt(req.files.length);
if(len === 20){
console.log('let us throw error');
}
cb(null, dest);
}
onError : function(err, next){
console.log('error' + err);
next(err);
}
}),
function(req, res) {
res.status(204).end();
}
});

使用 express-fileupload 使用 multer 指定技术进行验证

var multer = require('multer')
var upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
  if (err instanceof multer.MulterError) {
  // A Multer error occurred when uploading.
  } else if (err) {
  // An unknown error occurred when uploading.
  }

   // Everything went fine.
  })
})

为 console.log(req.files) 返回 null;

尝试了该线程中的几乎所有内容:File uploading with Express 4.0: req.files undefined

错误处理:

app.post('/upload',[
  multer({
    dest    : './uploads/1992-12-11/',
    onError : function(err, next) {
      console.log('error', err);
      next(err);
    }
 }),
 function(req, res) {
   res.status(204).end();
   }
 ]);

【问题讨论】:

    标签: node.js express multer


    【解决方案1】:

    由于您要上传多个文件,它应该是 multer 数组。 您可以像这样指定文件限制:

    var upload = multer().array('file', 20); // where 20 is the limit
    

    您的路由处理程序可以相同,并且可以在 if 中处理错误:

    app.post('/profile', function (req, res) {
      upload(req, res, function (err) {
      if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
      } else if (err) {
      // An unknown error occurred when uploading.
      }
       // Everything went fine.
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 2015-08-30
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2018-05-27
      相关资源
      最近更新 更多