Download files using express.js and node, limiting extensions

I am working on handling file uploads using express.js and node, and I have basic functionality. I need to implement some security measures, namely to limit the download to certain formats (PNG, JPEG). Is there an easy way to allow only certain formats? Will this go to the parser body?

app.use(express.bodyParser({ uploadDir: __dirname + '/public/uploads', keepExtensions: true })); app.use(express.limit('4mb')); 

Are there any other security measures I should consider? Is it a good idea to erase EXIF ​​data from an image?

Thanks,

Ben

+4
source share
2 answers

According to the documentation for connect bodyParser any options are also passed to formidable , which does the actual parsing.

According to formidable documents, you can pass your own onPart handler:

incomingForm.onPart (part)

You can overwrite this method if you are interested in directly accessing a multi-page stream. This will disable any field / file event processing that would otherwise occur, which is fully responsible for processing the processing.

 incomingForm.onPart = function(part) { part.addListener('data', function() { // ... }); } 

If you want to use formidable processing only for certain parts for you, you can do this:

 incomingForm.onPart = function(part) { if (!part.filename) { // let formidable handle all non-file parts incomingForm.handlePart(part); } } 

Taken together, you should do something like this:

 function onPart(part) { if(!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) { this.handlePart(part); } } app.use(express.bodyParser({onPart: onPart}); 

Warning: I have not tested this.

+5
source

I found a potential solution:

In your middleware

  if (req.files[key].type != 'image/png' && req.files[key].type != 'image/jpeg'){ res.send(403); } else { next(); } 

update: This does not actually stop the download of the file.

+2
source

All Articles