Reputation: 4461
As title says.
I looked everywhere, couldn't find an answer.
CODE:
var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 250000}}).single("image");
PROBLEM
This does not prevent me from uploading a pdf if I choose to do so.
Upvotes: 4
Views: 3004
Reputation: 6882
The docs state you should use fileFilter to possibly skip files for upload.
fileFilter (https://github.com/expressjs/multer#filefilter)
Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:
function fileFilter (req, file, cb) {
// The function should call `cb` with a boolean
// to indicate if the file should be accepted
// To reject this file pass `false`, like so:
cb(null, false)
// To accept the file pass `true`, like so:
cb(null, true)
// You can always pass an error if something goes wrong:
cb(new Error('I don\'t have a clue!'))
}
From the docs I would assume that the passed in file
has a property mimetype
(https://github.com/expressjs/multer#api). This could be a good hint for the decision if you want to skip.
EDIT: this GH issues (https://github.com/expressjs/multer/issues/114#issuecomment-231591339) contains a good example for the usage. It's important to not only look at the file extension because this can easily be renamed but also take the mime-type into account.
const path = require('path');
multer({
fileFilter: function (req, file, cb) {
var filetypes = /jpeg|jpg/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb("Error: File upload only supports the following filetypes - " + filetypes);
}
});
HTH
Upvotes: 6