我希望能够使用Node.js将PDF文件发送到前端。但是当我这样做时,会出现错误,无法打开文件。这是错误信息(翻译的错误信息:加载PDF文档时发生了错误):
我认为一切都正常,但仍无法正常工作。
以下是Node.js代码:
![enter image description here](https://istack.dev59.com/dyLXJ.webp)
以下是Node.js代码:
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();
});
};
不要担心所有像verifyJWT或ClassJWT这样的JWT,它们都是JSON Web Token的实现,可以正常工作。
如果有人知道如何修复它,请告诉我。
${path}${dirname}${training.file_id}
可能会产生比预期少的/
字符。我的第一个怀疑对象是dirname
没有以斜杠结尾。 - tevemadarres.download
而不是res.sendFile
? - Parzh from Ukraine