简体   繁体   English

如何从 NodeJS 服务器下载 React 中的文件? (使文件损坏)

[英]How to download files in React from NodeJS server? (Getting files corrupted)

I would like to be able to send pdf files with nodejs to the frontend.我希望能够使用 nodejs 将 pdf 个文件发送到前端。 But when I do this, I get an error and I can't open the file.但是当我这样做时,出现错误并且无法打开文件。 This is the error (translation of error: an error occurred when loading the PDF document):错误是这样的(错误翻译:加载PDF文档时出错): 在此处输入图像描述

I think that all is well but still without working.我认为一切都很好,但仍然没有工作。

Here is the nodeJS code:这是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}`);
  }
});

And here is the React frontend code:这是 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();
    });
  };

Don`t worry about all that have JWT like verifyJWT or ClassJWT, this are implementations of json web tokens and it works correctly.不要担心所有有 JWT 的东西,比如 verifyJWT 或 ClassJWT,这是 json web 令牌的实现,它可以正常工作。

If anyone know how to fix it, please let me know.如果有人知道如何修复它,请告诉我。

maybe you can try this也许你可以试试这个

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

I don't test it.我不测试它。

first of all you get file with id so the name of the file missing extension.pdf you can try this code first and setting custom name首先,您获得带有 id 的文件,因此文件名缺少扩展名。pdf 您可以先尝试此代码并设置自定义名称

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

if this is not working try to send file not download如果这不起作用,请尝试发送文件而不是下载

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

I think you need to change the response type to 'arraybuffer', responseType: 'arraybuffer' at least that work for me in a similar situation.我认为您需要将响应类型更改为“arraybuffer”, responseType: 'arraybuffer'至少在类似情况下对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM