在multer中使用文件过滤器时如何捕获错误?

Vis*_*hnu 2 file node.js filefilter multer

我已经搜索过但我找不到确切的解决方案..当我上传图像时,它应该只允许 jpg、jpeg、gif、png ..如果有任何其他文件,它应该在 UI 中显示消息。我使用了以下代码

var upload = multer({ storage: storage,
 fileFilter: function (req, file, cb) {
        var ext = path.extname(file.originalname);
        if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
             return cb(new Error('Wrong extension type'));
            // if(Error){
            //     console.log("error file type")
            // }

        }
        cb(null, true)
    }

});
Run Code Online (Sandbox Code Playgroud)

如果我尝试上传 pic 而不是 jpeg,jpg,png,git 它显示错误..但是如何在我的应用程序页面本身中显示为消息

Error: Wrong extension type
    at fileFilter (D:\Vishnu\octopus new\app\routes.js:912:24)
    at wrappedFileFilter (D:\Vishnu\octopus new\node_modules\multer\index.js:44:7)
    at Busboy.<anonymous> (D:\Vishnu\octopus new\node_modules\multer\lib\make-middleware.js:114:7)
    at emitMany (events.js:127:13)
    at Busboy.emit (events.js:201:7)
    at Busboy.emit (D:\Vishnu\octopus new\node_modules\busboy\lib\main.js:38:33)
    at PartStream.<anonymous> (D:\Vishnu\octopus new\node_modules\busboy\lib\types\multipart.js:213:13)
    at emitOne (events.js:96:13)
    at PartStream.emit (events.js:188:7)
    at HeaderParser.<anonymous> (D:\Vishnu\octopus new\node_modules\dicer\lib\Dicer.js:51:16)
    at emitOne (events.js:96:13)
    at HeaderParser.emit (events.js:188:7)
    at HeaderParser._finish (D:\Vishnu\octopus new\node_modules\dicer\lib\HeaderParser.js:68:8)
    at SBMH.<anonymous> (D:\Vishnu\octopus new\node_modules\dicer\lib\HeaderParser.js:40:12)
    at emitMany (events.js:127:13)
    at SBMH.emit (events.js:201:7)
Run Code Online (Sandbox Code Playgroud)

请帮助我解决这个问题.. 提前致谢

小智 11

我现在也一直在为这个问题苦苦挣扎。我以为我找到了一个解决方案,但它最终对我来说效果不佳,但是经过足够的修补和今晚环顾四周后,我找到了一个对我有用的答案。我希望这有帮助。我实际上是在四处寻找答案时发现了这个问题

所以我所做的是在您的示例中创建req.fileValidationError如下:

var upload = multer({ 
     fileFilter: function (req, file, cb) {
          let ext = path.extname(file.originalname);
          if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
               req.fileValidationError = "Forbidden extension";
               return cb(null, false, req.fileValidationError);
         }
         cb(null, true);
     }
});
Run Code Online (Sandbox Code Playgroud)

然后在您的路线中,您想使用 if 语句检查req.fileValidationError。如果它存在,那么你知道有一个禁止的扩展。

假设您在app变量下使用 express ,并且您想要发送单个图像,它看起来像这样:

app.post('/your-upload-route', upload.single("your-input-name-here"), function(req, res) {
     if (req.fileValidationError) {
          // return res.sendFile();
          // or return res.end();
          // or even res.render(); whatever response you want here.
     }
});
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!如果其他人有不同的方式来做这件事,我很乐意更新我的答案以及看到其他人的见解。