【问题标题】:How to download files in React from NodeJS server? (Getting files corrupted)如何从 NodeJS 服务器下载 React 中的文件? (获取文件损坏)
【发布时间】:2021-11-04 23:37:53
【问题描述】:

我希望能够将带有 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) {
   const path = "/home/gonsa02/Disk/Projects/";
   const dirname = "uploads/trainings/";
   res.download(`${path}${dirname}${training.file_id}`);
  }
});

这里是 React 前端代码:

const downloadTraining = async (id) => {
    const fileReader = new FileReader();
    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((res) => {
        console.log(res);
        fileReader.readAsDataURL(new Blob([res.data]));
      })
      .catch((err) => console.log(err));

    fileReader.addEventListener("loadend", () => {
      const blobString = fileReader.result;
      const link = document.createElement("a");
      link.href = blobString;
      link.setAttribute("download", "file.pdf");
      document.body.appendChild(link);
      link.click();
    });
  };

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

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

【问题讨论】:

  • ${path}${dirname}${training.file_id} 产生的/ 字符可能比预期的要少。我的第一个怀疑是dirname 不以斜线结尾。
  • 目录名是正确的,我会写变量以免让任何人感到困惑
  • 为什么是res.download,而不是res.sendFile
  • @DimaParzhitsky 因为我已经尝试过了,它也不起作用

标签: node.js reactjs


【解决方案1】:

也许你可以试试这个

fetch("filepath", {
  headers: headers
})
  .then(res => res.blob())
  .then(blob => {
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", "file.pdf");
    document.body.appendChild(link);
    link.click();
  })

我不测试它。

【讨论】:

    【解决方案2】:

    首先你得到带有 id 的文件,所以文件的名称缺少扩展名 .pdf 你可以先试试这个代码并设置自定义名称

       res.download(`${path}${dirname}${training.file_id}` , "test.pdf);
    

    如果这不起作用,请尝试发送文件而不是下载

    var data =fs.readFileSync(`${path}${dirname}${training.file_id}`);
    res.contentType("application/pdf");
    res.send(data);
    
    

    【讨论】:

    • 请检查 2 件事 1.检查您的最终目录并检查您的文件名称是用 {id} 保存的文件还是它们具有 .pdf 之类的扩展名,所以如果它们有扩展名,您应该在您的路径2.是将fs.readFileSync放入try catch并检查是否有任何错误并console.log数据并检查数据是否打印在您的控制台上
    • 最终目录正确,file_id包含文件的扩展名。另外,如果我通过带有 xdg-open 的 linux 终端打开它,并且我从 $ {path} $ {dirname} $ {training.file_id} 获得的路径正确打开了 pdf,所以理论上这是正确的
    • 此外,如果我在 React 前端收到 console.log(response.data),我会得到以下信息: data: "%PDF-1.5\n%����\n6 0 obj\n>\n流\nx��ZKs�6\u0012��W�M\u001c�\u0007�\u001b�}�8��+Q���� r�...所以文件被发送了
    猜你喜欢
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多