【问题标题】:How to send a pdf file from Node/Express app to the browser如何将 pdf 文件从 Node/Express 应用程序发送到浏览器
【发布时间】:2015-09-15 08:03:42
【问题描述】:

在我的 Node/Express 应用程序中,我有以下代码,假设从文件中读取 PDF 文档,并将其发送到浏览器:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf', 'binary');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
res.pipe(file, 'binary');
res.end(); 

我没有收到任何错误,但我也没有在浏览器中获取文件。 我做错了什么?

【问题讨论】:

  • 一个重要细节 - 我正在尝试将文件发送回浏览器以响应 http POST

标签: node.js express


【解决方案1】:

你必须从可读流到可写流,而不是相反:

var file = fs.createReadStream('./public/modules/datacollectors/output.pdf');
var stat = fs.statSync('./public/modules/datacollectors/output.pdf');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=quote.pdf');
file.pipe(res);

另外,如果您以错误的方式设置编码,请在需要时传递带有编码的对象。

【讨论】:

  • 现在我可以看到正在发送到浏览器控制台的文件内容,但该文件仍然没有作为附件“弹出”出浏览器。
  • 找到解决方案了吗?
  • @EugeneGoldberg 您可以使用此节点模块npmjs.com/package/file-saver 下载数据。您可以将数据转换为 blob,如下所示 var blob = new Blob([data], {type: "application/pdf"}); FileSaver.default(blob, fileNameWithExtension);
  • res.send(buffer) 用于缓冲区。
【解决方案2】:

我想我在另一篇帖子Display PDF file in a browser using node js 中找到了您的答案。

在 Chrome 中测试您的代码后,它会立即开始下载 PDF 文件。但如果您想显示 PDF 文件的内容,您可以尝试如下:

var data =fs.readFileSync('./public/modules/datacollectors/output.pdf');
res.contentType("application/pdf");
res.send(data);

这应该直接将 PDF 内容发送到浏览器。

希望这能回答你的问题。

【讨论】:

    【解决方案3】:

    这是最简单的方法:

    app.get('/', (req, res) => res.download('./file.pdf'))
    

    如果这给您带来麻烦。检查 Express.js 版本或任何可能需要的中间件。

    干杯

    【讨论】:

      【解决方案4】:

      在 REST API 调用上下载 PDF 的最佳方式。

      var path = require('path');     
      var file = path.join(__dirname, 'file.pdf');    
      res.download(file, function (err) {
             if (err) {
                 console.log("Error");
                 console.log(err);
             } else {
                 console.log("Success");
             }    
      });
      

      【讨论】:

        【解决方案5】:

        如果您使用的是 Swagger/OpenAPI,那么您可以查看以下代码的响应部分。 /api/pdf_from_html: post: tags: - PDF description: Create PDF from html produces: - application/pdf consumes: - application/json parameters: - name: contents description: HTML content to convert to pdf in: body required: true schema: $ref: "#/definitions/pdf" responses: 200: description: Returns a PDF encoded in base64 content: application/pdf: schema: type: string format: base64

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-17
          • 1970-01-01
          • 2010-10-18
          • 2014-04-17
          • 2019-02-21
          • 2020-06-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多