我已经搜索过,但找不到确切的解决方案。当我上传图像时,它应该只允许 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)
}
});
如果我尝试上传图片而不是 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)
请帮助我解决这个问题。提前致谢
最佳答案
我也被这个问题困扰了一段时间。我以为我找到了一个解决方案,但它最终对我来说效果不佳,但经过足够的修补和今晚的环顾后,我找到了一个适合我的答案。我希望这有帮助。 我实际上在寻找答案时发现了这个问题。
所以我所做的是在您的示例中创建了 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);
}
});
然后在您的 route ,您需要使用 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.
}
});
我希望这有帮助!如果其他人有不同的方法来做到这一点,我很乐意更新我的答案并了解其他人的见解。
关于node.js - 当我在 multer 中使用文件过滤器时如何捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47673533/