As question title explains, I need to filter uploaded files on the basis of file extension. So, I went through the official docs and searched this website.
What I've Tried
I've tried solutions I came across. Files are being successfully uploaded, but the problem is how to filter files. Currently my Router.js file looks like this.
Router.JS
var multer = require('multer');
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
limits:{
files: 1,
fileSize: 1024 * 1024
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
},
onFileUploadStart: function(file) {
console.log("Inside uploads");
if (file.mimetype == 'image/jpg' || file.mimetype == 'image/jpeg' || file.mimetype == 'image/png') {
return true;
}
else
{
return false;
}
}
});
var upload = multer({ //multer settings
storage: storage
}).single('profilepic');
router.post('/profile', function(req, res){
upload(req,res,function(err){
if(err)
{
console.log(err);
}
else
{
console.log("Image was uploaded");
}
});
});
I tried echoing something in onFileUploadStart
to check if it is going into that function or not. And it was not. Besides onFileUploadStart
, I also tried fileFilter
as mentioned at this link, but it was not helpful. Any suggestions how to solve this? Thanks in advance.
An example using multer
:
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
}
});
var upload = multer({ //multer settings
storage: storage,
fileFilter: function (req, file, callback) {
var ext = path.extname(file.originalname);
if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
return callback(new Error('Only images are allowed'))
}
callback(null, true)
},
limits:{
fileSize: 1024 * 1024
}
}).single('profilepic');
Excerpted from Node.js - File upload. The original authors were Iceman and Mikhail. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 4080 and example ID: 14210.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With