node.jsexpresslarge-file-upload

How do I set the bodyParser upload limit to specific routes rather than globally in the middleware?


Here's an example (Express 3) middleware setup thats worked for me globally:

app.configure(function () {
    app.use(express.static(__dirname + "/public"));
    app.use(express.bodyParser({
          keepExtensions: true,
          limit: 10000000, // set 10MB limit
          defer: true              
    }));
    //... more config stuff
}

For security reasons, I don't want to allow 500GB+ posts on routes other than /upload, so I'm trying to figure out how to specify the limit on specific routes, rather than globally in the middleware.

I know the multipart middleware in bodyParser() already sniffs out content types, but I want to limit it even further.

This does not seem to work in express 3:

app.use('/', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 10,
  defer: true              
}));
app.use('/upload', express.bodyParser({
  keepExtensions: true,
  limit: 1024 * 1024 * 1024 * 500,
  defer: true              
}));

I get an error Error: Request Entity Too Large when I try to upload a 3MB file on the upload URL.

How do you do this correctly?


Solution

  • Just specify the optional path option when using app.use().

    app.use('/', express.bodyParser({
      keepExtensions: true,
      limit: 1024 * 1024 * 10,
      defer: true              
    }));
    app.use('/upload', express.bodyParser({
      keepExtensions: true,
      limit: 1024 * 1024 * 1024 * 500,
      defer: true              
    }));