Reputation: 7562
I'm using multer to upload files in nodejs. Below is my code.
var multer = require('multer');
var imagefolder = __base + 'public/complaintimages';
var storage = multer.diskStorage({
destination: function (req, file, cb) {
if (common.ImageMimeTypes.indexOf(file.mimetype) < 0) {
common.ActionOutput.Status = common.ActionStatus.Error;
common.ActionOutput.Message = 'Invalid image file: ' + file.originalname;
cb(new Error(JSON.stringify(common.ActionOutput)), null);
} else
cb(null, imagefolder);
},
filename: function (req, file, cb) {
var filenm = randomstring.generate(10);
console.log(filenm + file.originalname);
cb(null, filenm + file.originalname);
},
onError: function (err, next) {
console.log('error', err);
next(err);
}
})
var upload = multer({ storage: storage });
I only allowed jpg files to upload by putting the mime type check which is working fine.
But when i upload any other type of file, control does not go into onError block so that i can return a proper validation message to the user like 'please upload valid jpg files.
'
Please advise.
Upvotes: 0
Views: 5102
Reputation: 8295
A different approach for the upload validation, use the fileFilter
callback https://github.com/expressjs/multer#filefilter.
It is actually quite complicated to decide what is the file actual type, so instead of using mime type use the (Detect the file type of a Buffer/Uint8Array) https://github.com/sindresorhus/file-type. It's a better approach then deciding based on the mime type, but does not guarantee that it has been faked.
Upvotes: 1