Thursday 20 April 2017

How to handle errors with multer?

I need to upload images on server, but if it is not jpeg\png, or filesize > 10Mb, I need to show an error. Images uploading well, but when I am trying to upload .zip file, my console is empty, why my code can't handle an error?

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);
});



via Bim Bam

No comments:

Post a Comment