【发布时间】:2017-04-21 07:45:37
【问题描述】:
我需要在服务器上上传图片,但如果不是 jpeg\png,或者文件大小 > 10Mb,我需要显示错误。图片上传很好,但是当我尝试上传 .zip 文件时,我的控制台是空的,为什么我的代码无法处理错误?
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../public/img/avatars')
},
filename: function (req, file, cb) {
cb(null, ''+req.user._id+'')
},
fileFilter: function (req, file, cb) {
if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/gif' ) {
console.log('Wrong format!');
return cb(null, false, new Error('Wrong format!'));
}
if ( file.size > 10000 ){
console.log('Too large!');
return cb(null, false, new Error('Too large!'));
}
cb(null, true);
}
});
var upload = multer({ storage: storage });
router.post('/changeAvatar', upload.single('avatar'), function(req, res) {
var id = req.user._id;
res.redirect('/user/'+id);
});
【问题讨论】: