在快速路线响应中发送PDF并强制浏览器下载

时间:2018-05-10 04:57:45

标签: node.js express

背景

我正在快速服务器上生成PDF并将其保存到本地目录。在回调中,我试图将PDF发送回服务器,因此它将下载,但它似乎是网络选项卡响应,因为它似乎是二进制的,不会下载。

示例

编辑我的客户端功能提供服务器请求 此提取调用会触发应返回PDF的快速结束点。快递路线如下,

function setImage() {
  html2canvas(document.querySelector('#chart')).then(canvas => {
    canvas.toBlob(
      function(blob) {
        const url = 'http://localhost:3000/api/v1/pdf';

        fetch(url, {
          method: 'POST',
          headers: {
            'Content-type': 'application/octet-stream',
          },
          body: blob,
        })
          .then(response => response.json())
          .then(success => console.log(success))
          .catch(error => console.log(error));
      },
      'image/png',
      1,
    );
    document.body.appendChild(canvas);
  });
}

// 创建PDF并将其保存在filePath

的服务器上
router.post('/', (req, res, next) => {
      pdf.create(html, options).toFile(filePath, err => {

            if (err) {
              return console.log(err);
            }
            const stat = fs.statSync('./downloads/report.pdf');
            res.contentType('application/pdf');
            res.setHeader('Content-Length', stat.size);
            res.setHeader('Content-Type', 'application/pdf');
            res.setHeader('Content-Disposition', 'attachment; filename=report.pdf');
        // *Should force download the file to the browser*
            res.download('../downloads/report.pdf', 'report.pdf', function(e) {
              if (e) {
                // Handle error, but keep in mind the response may be partially-sent
                // so check res.headersSent
              } else {
                // It worked, do something else.
              }
            });
          });
    });

编辑我也在服务器上试过这个,它在浏览器中显示响应,但不会下载文件。

router.post('/', (req, res, next) => {
  const img = req.body;
  const filepath = 'uploads/chart.png';
  fs.writeFile(filepath, img, err => {
    if (err) {
      throw err;
    }
    console.log('The file was succesfully saved!');
  });

  const html = tmpl.replace('{{chart}}', `file://${require.resolve('../uploads/chart.png')}`);
  const options = { format: 'Letter' };
  const fileName = 'report.pdf';
  const filePath = './downloads/report.pdf';

  pdf.create(html, options).toFile(filePath, err => {
    if (err) {
      return console.log(err);
    }
    const stat = fs.statSync('./downloads/report.pdf');
    res.setHeader('Content-Description', 'File Transfer');
    res.setHeader('Content-Length', stat.size);
    res.setHeader('Content-type', 'application/octet-stream');
    res.setHeader('Content-type', 'application/pdf');
    res.setHeader('Content-Type', 'application/force-download');
    res.setHeader('Content-disposition', 'attachment;filename=report.pdf');

    res.sendFile('/downloads/report.pdf');
  });

浏览器输出示例

enter image description here

问题

Express 4强制浏览器下载PDF的正确方法是什么?

0 个答案:

没有答案