【问题标题】:Get File from external URL with fs.readFile使用 fs.readFile 从外部 URL 获取文件
【发布时间】:2016-07-09 18:04:37
【问题描述】:

我的页面上有链接,点击后我希望打开一个外部 docx 文件。不幸的是,fs.readFile 只读取本地路径。

我试过了

app.get('/getfile', function (req, res) {
   var externalURL = 'http://www.examplesite.com/example.docx';
   // var externalURL = req.query.external;
   fs.readFile(externalURL, function(err, data) {
      var fileData = new Buffer(data).toString('base64');
      res.send(fileData);
   });
});

【问题讨论】:

  • 使用您发布的代码时会出现什么错误/输出
  • SCRIPT7002:XMLHttpRequest:网络错误 0x2efd,由于错误 00002efd 无法完成操作。
  • 那有用吗?标记为解决该问题。
  • @TiagoFabre 这只会创建文件,但你能在原始 docx 文件中获取数据并将其导入新文件中吗?

标签: node.js express


【解决方案1】:

试试这个:

const http = require("http");
const file = fs.createWriteStream("file.docx");

http.get("http://www.example.com/test.docx", response => {
  response.pipe(file);
});

【讨论】:

  • “ReadStream”类型的参数不能分配给“WritableStream”类型的参数。
  • 我不明白?(这里是新手)。您能否在问题代码的上下文中将其作为一个完整的示例来展示?
【解决方案2】:

试试node-fetch。 它遵循 fetch 命令的常规客户端语法 (MDN)。

【讨论】:

  • 请使用 node-fetch 提供您的解决方案
【解决方案3】:

我建议使用request 来做。

我不知道你是这个意思...

试一试:

const request = require('request');

request.get('http://examplesite.com/example.docx', function(err, res, body) {
  // Body is the example.docx data.

})

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 2021-08-13
    • 2019-11-14
    • 2012-04-20
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多