Prevent upload too big

I'm uploading a base64 string of an image to my node.js server. How do I prevent in my node.js server from this file being bigger than 1mb and from having more than 200px by 200px (without actually converting and/or saving the file/string) ?

This is kinda the pseudocode:

  • Browswer has a base64 string image
  • Browser makes a POST request to a node.js server and sends the base64 image string in thebody

  • while(node.js receives request) { if (request>1mb) stop receiving the request/close conection }

  • save file

Thanks :D

Short answer (aug 2014): app.use(bodyParser.json({ limit: '1mb' }))

Personally, I'd deploy nginx in front of node.js and leave the control to nginx, you use this directive client_max_body_size 1m; in the http{...} block.

The 200px by 200px is impossible to determine since a mostly white pic can have larger dimensions, yet fit inside 1mb. Hence the only workaround is to check the width and height, and scale it down if it is too large.

Note: base64 encoded images is enlarged by 33%