node.js - Node/Express:stream.pipe()上没有下载

标签 node.js express download streaming

当我通过流响应时,有什么方法可以强制下载?
如果我查看Chrome工具,会发现响应很好,标题也不错:

HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/pdf
Date: Mon, 10 Oct 2016 20:22:51 GMT
Transfer-Encoding: chunked
Via: 1.1 vegur
Request Headers
view source

我什至在详细响应中都看到了pdf文件代码,但是没有启动文件下载。也许我想念什么?

我的路线代码如下:
router.post('/reports/create', access.Regular, function (req, res, next) {
    ...

    pdf.create(html).toBuffer(function(err, buffer){
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename=some_file.pdf',
            'Content-Length': buffer.length
        });
        res.end(buffer)
    });
});

最佳答案

您需要添加 Content-Disposition header ,以向浏览器发出信号,表明需要下载附件。

app.get('/:filename', (req, res) => {
  // Do whatever work to retrieve file and contents      

  // Set Content-Disposition Header on the response
  // filename is the name of the file the browser needs to download when 
  // receiving  the response to this particular request
  res.setHeader('Content-Disposition', `attachment; filename=${req.params.filename}`);

  // stream the fileContent back to the requester
  return res.end(fileContent)
});

关于node.js - Node/Express:stream.pipe()上没有下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39966311/

相关文章:

node.js - readFileSync 未将 URL 读取为文件

node.js - 从 Node.js 公开方法的最佳方式是什么?

node.js - 错误: Fontconfig warning: ignoring UTF-8: not a valid region tag

node.js - Pro.find is not a function error in mongoose 模型导出

c# - 向用户界面报告下载进度

java - Android - 大文件下载停止 - 使用异步/进度对话框

javascript - 多次调用另一个js文件的生成器函数并与生成器同步运行

mysql - ER_PARSE_ERROR : You have an error in your SQL syntax;

javascript - 从内存(而不是数据库)提供后端数据

jquery - 在 Javascript/jQuery 中解码 base64 文件以供下载