Simple File Uploads with Node.js & Express

A quick example of how to get a file upload up & running using Express with Node.js when you need to handle some file processing on the server.

Code

package.json

1
"express": "3.2.6",

Jade

1
2
form(action="/upload", method="post", enctype="multipart/form-data")
input(type="file", id='file-upload-input', onchange="this.form.submit()", name="document-upload")

Node.js

1
app.post('/upload', uploader.uploadDocument);
1
2
3
exports.uploadDocument = function(req, res) {
// Do something with req.files
}

Gotchas

Missing name attribute

1
Error: parser error, 40 of 44 bytes parsed

Inputs submitted without a name attribute will spit out a rather unhelpful trace. Double check name is set on the input element itself.

req.files undefined or empty

As of Express 4.x, the middleware for processing multipart/form-data was removed from the bodyParser middleware, leaving only the application/x-www-form-urlencoded and application/json body data parsers.

If you can skip back to Express 3.x then hey presto, otherwise there are plenty of custom parsers for handling multipart such as multer or busboy

Comments