I google a lot for finding how to secure file uploading in express js,at end I develop following code to do it.
app.use(express.json());
app.use(express.urlencoded());
app.post('/',express.bodyParser({
keepExtensions: true,
uploadDir: __dirname + '/faxFiles',
limit: '20mb'
}),function(req,res){
checkFile(req.files.faxFile);
});
as you see I can limit file size and set uploadDir in bodyParser,now I need to allow user to upload image and pdf only,the way I used is checkFile function which contains following code.
var fs = require('fs');
var checkFile = function(faxFile){
if (faxFile.type != "image/jpeg" || faxFile.type != "application/pdf" || faxFile.type != "image/gif"){
fs.unlink(faxFile.path, function(err){
});
}
}
but I think it's not best way,is there any alternative way to do it?such as set file extension in bodyParser constructor?
Express uses formidible (https://github.com/felixge/node-formidable) for parsing form data, including file uploads.
I don't see an option in formidible to restrict file types, so I'm suggesting Express likely wouldn't have one either.
You can use mmmagic for strictly checking the extensions. It is an async libmagic binding for node.js for detecting content types by data inspection.
I created a little gist to show how to check the mime type using mmmagic while streaming the file:
https://gist.github.com/chmanie/8520572
This is more likely to function in a streaming environment like multiparty or busboy.