node.js - 如何读取从Web客户端发送的nodejs服务器中的文件

标签 node.js file-io

我是 nodeJS 和 Java Script 的新手。 我需要实现一种机制来读取从 Web 客户端发送的 nodeJS 服务器中的文件。

任何人都可以指导我如何做到这一点吗? 我在 nodeJS 文件系统中找到了 readFileSync(),它可以读取文件的内容。但是如何从 Web 浏览器发送的请求中检索文件呢?如果文件很大,那么在 nodeJS 中读取该文件内容的最佳方法是什么?

最佳答案

formidable是一个非常方便的处理表单的库。

以下代码是一个功能齐全的示例 Node 应用程序,我从 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);

这显然是一个非常简单的示例,但 formidable 也非常适合处理大文件。它使您可以访问已处理的已解析表单数据的读取流。这使您可以在数据上传时对其进行处理,或将其直接通过管道传输到另一个流中。

// 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();

关于node.js - 如何读取从Web客户端发送的nodejs服务器中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13619336/

相关文章:

node.js - Node js中基于关系的ACL

javascript - NodeJS 与 Express : Header undefined

node.js - angular2 快速入门推荐的所有依赖项真的有必要吗?

c - 是否可以将标准输入/输出设置为 C 中的文件?

node.js - 无法迁移到 Angular 5,在 Angular 文件上出现无效错误

C# UWP : copy file to folder inside local folder not functioning properly

python - 打开文件进行读/写,如果需要则创建

C++ FileIO 读取和写入对象变量

python paramiko与文件输入连接

javascript - 批量发送 API 调用