我有一个返回 File(byte[], "application/pdf") | 的 API来自服务器的字节[]。
在前端部分,我创建一个请求,并可以将此文件(如 pdf 文件)保存到计算机上,但我需要存储此文件(状态或其他方式)并在 React 组件内渲染(如 PDF 文件) ,它可以放在 iframe 或其他方式上(对我来说这并不重要,只需要从 API 获取文件后在组件内渲染即可)。
const instance = axios.create({
baseURL: process.env.REACT_APP_API_ROOT,
headers: {
"Content-Type": "application/json",
},
});
function getPdfByFileName(fileName: string): any {
return instance.get(`pdfs/${fileName}`);
}
function getPdfAsBlobByFileName(fileName: string): any {
return instance.get(`pdfs/${fileName}/array`);
}
useEffect(() => {
getPdfByFileName("fileName")
.then((response: AxiosResponse) => {
// const file = new Blob([response.data], { type: "application/pdf" }); // For API which returns blob
setPdf(response.data); // Need store file and correct render like PDF
})
.catch((err: AxiosError) => {
// process err
});
}
}, []);
return (
<div>
<iframe title="pdf" width="100%" height="600px" srcDoc={pdf}></iframe>
</div>
);
结果:Inside component I render the data but it's no PDF
我已经尝试过了:
- 在这些请求中使用“Content-Type”:“application/pdf”。
- 将文件的 URL 放入 Iframe src 属性中(它适用于 匿名,但我们有 Bearer 并且需要保护数据)。
- 从 Blob API 响应生成 URL 并放入 Iframe(不起作用)。
- 不同的 pdf 查看器,它们可以根据文件路径很好地处理物理 PDF 文件,但不适用于我的情况。
感谢您的帮助。
最佳答案
对我来说,问题出在 axios 上,响应不正确,我只是切换到使用 fetch 方法,然后这种情况开始对我来说正确,与 axios 一样对我不起作用
const request = new Request(`URL_TO_API`,
{
method: "GET",
headers: {
Authorization: `Bearer ${accessToken}`,
},
mode: "cors",
cache: "default",
}
);
fetch(request)
.then((response) => response.blob())
.then((blob) => {
const file = window.URL.createObjectURL(blob);
const iframe = document.querySelector("iframe");
if (iframe?.src) iframe.src = file;
})
.catch((err: AxiosError) => {
// process error
});
return (
<div>
<iframe src="" width="100%" height="100%"></iframe>
</div>
);
关于javascript - 根据 API 响应在组件内 React 渲染 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71180728/