【问题标题】:How to download files with NodeJS backend and React frontend? (I get the files corrupted)如何使用 NodeJS 后端和 React 前端下载文件? (我的文件损坏了)
【发布时间】:2021-09-05 01:35:31
【问题描述】:

我希望能够将带有 nodejs 的 pdf 文件发送到前端。但是当我这样做时,我得到一个错误,我无法打开文件。这是错误(错误的翻译:加载 PDF 文档时发生错误):

我认为一切都很好,但仍然没有工作。

这里是nodeJS代码:

routerTrainer.get("/download-training", verifyJWT, async (req, res) => {

  const { training_id } = req.headers;

  let training = await Training.findOne({
    where: { id: training_id },
  });

  if (training) {
   res.download(`${path}${dirname}${training.file_id}`);
  }
});

这里是 React 前端代码:

const downloadTraining = async (id) => {
    const JWT = new ClassJWT();
    const axiosReq = axios.create();
    await JWT.checkJWT();
    axiosReq
      .get(`${serverPath}/download-training`, {
        headers: {
          training_id: id,
          token: JWT.getToken(),
          responseType: "blob"
        },
      })
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", "file.pdf");
        document.body.appendChild(link);
        link.click();
      })
      .catch((err) => console.log(err));
  };

不要担心所有有 JWT 的东西,比如 verifyJWT 或 ClassJWT,这是 json Web 令牌的实现,它可以正常工作。

如果有人知道如何解决它,请告诉我。

【问题讨论】:

标签: node.js reactjs


【解决方案1】:

您必须将二进制文件转换为 blob(在此示例中将 xhr 的 responseType 设置为 blob),然后将其转换为 base64 编码文件,这是一个示例:

<html>
  <body>
    <h1><a>dl</a></h1>

    <script>
      const pdfSrc = "https://blahblah.com/e-book.pdf";
      const linkTag = document.querySelector("a");
      const xhr = new XMLHttpRequest();
      const fileReader = new FileReader();

      xhr.open("GET", pdfSrc);
      xhr.responseType = "blob";

      xhr.addEventListener("loadend", () => {
        fileReader.readAsDataURL(xhr.response);
      });

      fileReader.addEventListener("loadend", (event) => {
        const base64File = event.srcElement.result;
        linkTag.href = base64File;
        linkTag.setAttribute("download", "file.pdf");
      });
      xhr.send();
    </script>
  </body>
</html>

【讨论】:

  • 对不起我的无知,但我不知道如何将你的代码应用到我的,我觉得你不使用 axios 而我这样做很困惑,你介意用我的代码做这个例子吗?很抱歉给您带来不便。
  • @Gonsa02 为什么不呢,看看这个:pastebin.com/eiXid3GL
  • 感谢代码,但是当我执行该函数时,我收到此控制台错误:TypeError:无法在“FileReader”上执行“readAsDataURL”:参数 1 不是“Blob”类型。我使用了 res.download() 可能不是 blob,我该如何发送 blob?
  • 我也是用的下载方式,没问题;也许你应该发布一个关于这个错误的新问题......
  • 我已经完成了 fileReader.readAsDataURL(new Blob([res.data])) 现在它正在下载,但我下载的 pdf 出现同样的错误:加载 PDF 文档时发生错误
猜你喜欢
  • 2020-11-10
  • 2018-03-20
  • 2019-03-10
  • 2017-09-13
  • 2018-04-08
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2016-03-20
相关资源
最近更新 更多