我是 nodeJS 和 Java Script 的新手。我需要实现一种机制来读取从 Web 客户端发送的 nodeJS 服务器中的文件。
谁能给我一些指示如何做到这一点?我readFileSync()
在 nodeJS 文件系统中找到了可以读取文件内容的文件。但是如何从 Web 浏览器发送的请求中检索文件呢?如果文件很大,那么在 nodeJS 中读取该文件内容的最佳方法是什么?
formidable是一个非常方便的用于处理表单的库。
下面的代码是一个功能齐全的示例节点应用程序,我取自 formidable 的 github 并稍作修改。它只是在 GET 上显示一个表单,并在 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(
'<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);
这显然是一个非常简单的示例,但对于处理大文件也非常有用。它使您可以访问处理的已解析表单数据的读取流。这允许您在上传数据时处理数据,或将其直接通过管道传输到另一个流中。
// 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();
您将需要解析可以包含来自 HTML 文件输入的文件的 http 请求的正文。例如,当使用带有 node 的 express web 框架时,您可以通过 HTML 表单发送 POST 请求并通过 req.body.files 访问任何文件数据。如果您只是使用节点,请查看“net”模块以帮助解析 http 请求。