Reputation: 483
During file upload I want to validate the file size, make sure that the uploaded file is an actual image and last but not least validate that a title has been written for the image. But this code doesn't work. What should I do?
var multer = require('multer'),
upload = multer({
dest: 'uploads/',
onFileUploadStart: function(file, req, res){
if(file.size > 1000000) {
res.send("Maximum picture size is 1 MB");
return false;
}
if(req.body.postname === ''){
res.send("Enter a title name for your post");
return false;
}
if(file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg'){
res.send("Supported image files are jpeg, jpg, and png");
return false;
}
}
});
And this is the route that gets the request through the form.
router.post('/uploadpost', upload.single('image'), function(req, res){
fs.rename(req.file.path, req.file.destination + req.file.originalname, function(err){
if(err){
throw err;
}
});
var postObj = {
Title : req.body.postname,
Img_path : req.file.destination + req.file.originalname
}
var query = connection.query('INSERT INTO posts SET ?', postObj, function(err, result){
if(err){
throw err;
}
});
Upvotes: 1
Views: 1813
Reputation: 5265
The multer
middleware has always had a pretty vague API documentation, but after some digging I found that it uses busboy
behind the scenes and that it pipes the limits
option object to Busboy
.
So to summarize, there is no onFileUploadStart
option, but there is a limits
property in the options object that you can define. Now if I understand everything correctly, you could do with this:
var multer = require('multer');
upload = multer({
dest: 'upload/',
limits: {
fileSize: 1000000
}
});
If you need more configuration options for the limits
object, there is documentation available on Busboy's GitHub Repo
Hope this helps!
Upvotes: 1