我无法在新窗口中显示从服务器获取的PDF文件



我的服务器中有pdf,我将其发送到客户端。我进入blob并从中获取URL,我使用该URL在新窗口中打开。它显示的页面类似于

%PDF-1.4
1 0 obj
<<
/Title (��)
/Creator (��)
/Producer (���Q�t� �5�.�5�.�1)
/CreationDate (D:20211128130647)
>>
endobj
2 0 obj
<<
/Type /Catalog
/Pages 3 0 R
>>
endobj
4 0 obj .....

我的代码

axios
.post(DOMENNAME + "/API/getPdf", { responseType: 'blob', body: id })
.then((res) => {
const url = window.URL.createObjectURL(new Blob([res.data],{type: "application/pdf"}));
window.open(url);
})
.catch((e) => {
console.log(e.message);
dispatch(getPdfFailure());
});

服务器路径

module.exports.taskGetPdf=(req,res)=>{
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "GET, OPTIONS");
res.set("Access-Control-Allow-Headers", "Content-Type");
res.sendFile("result38555.pdf", { root: __dirname })

问题出在请求方法上,我应该使用GET请求而不是POST。然后我改变了一切。

export const getPdf = (id) => {
return (dispatch) => {
axios
.get(DOMENNAME + "/API/getPdf" + "/" + id, {
responseType: "blob",
})
.then((res) => {
let blob = new Blob([res.data], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
let newWin = window.open();
newWin.location.href = url;
})
.catch((e) => {
console.log(e.message);
dispatch(getPdfFailure());
});
};
};

服务器

module.exports.taskGetPdf = (req, res) => {
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "GET, OPTIONS");
res.set("Access-Control-Allow-Headers", "Content-Type");
console.log(req.params.id);
res.sendFile(`result${req.params.id}.pdf`, { root: __dirname });
};

最新更新