我有一个返回 File(byte[], "application/pdf") | 的 API 来自服务器的字节[]。
在前端部分,我创建一个请求,并且可以像 pdf 文件一样将此文件保存到计算机上,但是我需要 存储此文件(状态或其他方式)并像 PDF 文件一样在 React 组件中渲染,它可以放在 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>
);
我已经尽力了:
感谢您的帮助。
对我来说,问题出在 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>
);
尝试一下它在我的应用程序中的工作