Issue
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):
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.
Solution
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.
Answered By - yuhengshen
Answer Checked By - - Willingham (ReactFix Volunteer)