节点/快速:无法在stream.pipe()

时间:2016-10-10 20:32:41

标签: 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)
    });
});

2 个答案:

答案 0 :(得分:0)

您需要添加Content-Disposition标题,以向浏览器发出附加内容需要下载的信息。

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)
});

答案 1 :(得分:0)

它对我有用:

var html = '<h1>Hello World</h1>';
let options = {
   format: 'Letter',
   border: '1cm'
};
pdf.create(html, options).toBuffer(function (err, Buffer) {
        if (err) {
            res.json({
            data: 'error PDF'
            })
        } else {
            res.set({
                'Content-Disposition': 'attachment; filename=test.pdf',
                'Content-Type': 'application/pdf; charset=utf-8'
            });
            res.write(Buffer);
            res.end();
        }
    });