如何上传文件然后在 Node.Js Express 应用程序中显示其内容?

How to upload a file and then display its contents in Node.Js Express app?

我很长时间以来一直在寻找这个问题的答案:我需要通过我的 Node.Js express 应用程序上传一个 text/html 文件,并将其内容保存到一个变量中进一步治疗。

当然,我可以制作多部分表格和 post 内容,但到目前为止我可以访问的只是 req.files,其中包含有关文件的信息,但不是实际内容.

如何从文件中获取实际的 text/html 内容?

我不想将它保存到我的服务器,只是将内容传递到我的应用程序并删除文件,所以我不想使用像 formidable 这样的模块。

有人可以帮忙吗?

谢谢!

使用 multer https://github.com/expressjs/multer 和选项 inMemory: true

作为一个粗略的例子,你会想做这样的事情。

app.post('test', function(req, res, next) {
  var result = ''; 
  multer({
    inMemory: true,
    onFileUploadData: function(file, data) {
      result += data;
    },  
    onFileUploadComplete: function(file) {
      console.log(result); // This is what you want
    }   
  })(req, res, next);
});

该文件默认保存在临时文件夹(可能是/tmp)中。您需要打开该文件,读取其内容,然后将其删除。

您需要使用这个 API:http://nodejs.org/api/fs.html

你可以这样做:

fs = require('fs');

fs.readFile(req.files.path, function (err, data) {
  if (err) throw err;
  // data will contain your file contents
  console.log(data)

  // delete file
  fs.unlink(req.files.path, function (err) {
    if (err) throw err;
    console.log('successfully deleted ' + req.files.path);
  });      
});