我希望能够将带有 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();
});
};
不要担心所有像 verifyJWT 或 ClassJWT 这样的 JWT,这是 json web 令牌的实现,它可以正常工作。
如果有人知道如何修复它,请告诉我。
也许你可以试试这个
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();
})
我不测试它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句