formidable is a very handy library for working with forms.
The following code is a fully functional example node app which I took from formidable's github and slightly modified. It simply displays a form on GET, and handles the upload from the form on POST, reading the file and echoing its contents:
var formidable = require('formidable'),
http = require('http'),
util = require('util'),
fs = require('fs');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
// The next function call, and the require of 'fs' above, are the only
// changes I made from the sample code on the formidable github
//
// This simply reads the file from the tempfile path and echoes back
// the contents to the response.
fs.readFile(files.upload.path, function (err, data) {
res.end(data);
});
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
This is obviously a very simple example, but formidable is great for working with large files too. It gives you access to a read stream of the parsed form data as it's handled. This allows you to work with the data as it's being uploaded, or pipe it directly into another stream.
// As opposed to above, where the form is parsed fully into files and fields,
// this is how you might handle form data yourself, while it's being parsed
form.onPart = function(part) {
part.addListener('data', function(data) {
// do something with data
});
}
form.parse();