formidable是一个使用表单非常方便的库。
下面的代码是一个功能齐全的示例节点应用程序,我从强大的github中取得并稍作修改。它只是显示上看到一个表单,并处理从POST形式上传,阅读文件和呼应其内容:
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(
'
'+'
'+
'
'+
''+
'
');
}).listen(8080);
这显然是一个很简单的例子,但对于大型文件强大是伟大的太。它使您可以访问解析后的表单数据的读取流。这使您可以在数据上传时处理数据,或者直接将数据输入到另一个数据流中。
// 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();