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

Viewed 706

I would like to be able to send pdf files with nodejs to the frontend. 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): enter image description here

I think that all is well but still without working.

Here is the nodeJS code:

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:

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.

If anyone know how to fix it, please let me know.

2 Answers

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

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

Related