如何处理multer的错误?

时间:2017-04-20 23:34:27

标签: node.js express multer

我需要在服务器上传图片,但如果不是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);
});

1 个答案:

答案 0 :(得分:0)

完成。只需从存储功能中删除fileFilter。

    var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../public/img/avatars')
    },
    filename: function (req, file, cb) {
        cb(null, ''+req.user._id+'')
    }
});
function fileFilter(req, file, cb) {
    if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/gif' ) {
        console.log('Неправильный формат изображения!');
        return cb(null, false);
    }
    if ( file.size > 10000 ){
        console.log('Изображение весит слишком много!');
        return cb(null, false);
    }
    cb(null, true);
}

var upload = multer({ storage: storage, fileFilter: fileFilter });