将pdf文件从nodejs发送给用户到reactjs

Abd*_*had 3 node.js reactjs

我在服务器端的文件系统中存储了 pdf 文档。

我需要让用户在他/她点击下载时下载其中之一。

问题是我知道如何将文件从 NodeJS 发送到浏览器,但这里的请求将由 ReactJS axios 请求发出。因此,当我发送文件时,响应将做出反应。如何将该pdf文件发送给用户?我是否可以使用前端代码直接访问文件系统?

当我res.sendFile(file_path)在 NodeJS 中执行后记录响应时,我在浏览器控制台中得到以下信息

在此处输入图片说明

我如何处理这个以便我可以让用户下载 pdf?

Vas*_*las 6

您可以使用文件保护程序下载文件。以下是我用于 pdf 下载的功能。(response.data是nodejs作为响应发回的缓冲区)

import FileSaver from 'file-saver';
...

_onPdfFetched() {
  FileSaver.saveAs(
    new Blob([response.data], { type: 'application/pdf' }),
    `sample.pdf`
  );
}
Run Code Online (Sandbox Code Playgroud)

或者你可以只向用户显示 pdf

window.open(response.data, '_blank');
Run Code Online (Sandbox Code Playgroud)

编辑

axios 调用应该是这样的:

axios.get(url, {
  responseType: 'arraybuffer',
  headers: {
      Accept: 'application/pdf',
  },
});
Run Code Online (Sandbox Code Playgroud)

编辑 2

nodejs 代码应该是这样的:

router.post('/api/downloadfile',(req, res, next) => {
  const src = fs.createReadStream('path to sample.pdf');

  res.writeHead(200, {
    'Content-Type': 'application/pdf',
    'Content-Disposition': 'attachment; filename=sample.pdf',
    'Content-Transfer-Encoding': 'Binary'
  });

  src.pipe(res); 
});
Run Code Online (Sandbox Code Playgroud)