Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

uploading files using express.js and node, limiting extensions

uploading files using express.js and node, limiting extensions


I'm working on handling file uploads using express.js and node, and have the basic functionality working. What I need is to implement some security measures -- namely, to limit uploads to certain formats (PNG, JPEG). Is there an easy way to only allow certain formats? Would it go in the body-parser?

    uploadDir: __dirname + '/public/uploads',
    keepExtensions: true   }));


Are there any other security measures that I should take into account? Is it generally a good idea to wipe EXIF data from the image?



Problem courtesy of: bento


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

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


You may overwrite this method if you are interested in directly accessing the multipart stream. Doing so will disable any 'field' / 'file' events processing which would occur otherwise, making you fully responsible for handling the processing.

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

If you want to use formidable to only handle certain parts for you, you can do so:

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

Taken together, you should be able to do something like this:

function onPart(part) {
    if(!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) {

app.use(express.bodyParser({onPart: onPart});

Warning: I haven't tested any of this.

Solution courtesy of: Linus Gustav Larsson Thiel


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

uploading files using express.js and node, limiting extensions


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription