记录一个将后端返回 pdf blob 格式文件展示在页面上
我们后端返回的是数据流不是地址!
当前项目中使用的是已经封装过的 axios 请求,但不重要,重要的是使用 ` responseType: "blob" ` 获取二进制数据
export function qwe(data) {
return request({
url: "/qwe/qwe/qwe", // 更改为自己的接口
responseType: "blob", // 获取二进制数据
method: "post",
data,
});
}
// 这是一个没有封装过的 axios 示例
axios({
method: 'get || post', // 请求类型 get || post 按照后端来
url: 'qwe',
responseType: 'blob' // 设置响应类型为blob
})
.then(response => {
})
.catch(error => {
console.error(error);
});
照搬复制可获取到数据后打开新页面并将 PDF 展示出来,记得接口还有函数名称及参数改成自己的
detail(row) {
qwe({ id: row.id }).then((blob) => {
const reader = new FileReader();
reader.onloadend = () => {
const pdfData = reader.result;
const pdfBase64 = btoa(pdfData);
const htmlContent = `
<html style="width: 100%;height: 100%">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${row.name}</title> // 这里可以更改新标签页的title名称
</head>
// 给出宽高并清除浏览器默认样式
<body style="width: 100%;height: 100%;padding: 0;margin: 0;">
<embed
src="data:application/pdf;base64,${pdfBase64}"
type="application/pdf"
style="width: 100%;height: 100%"
/>
</body>
</html>
`;
const newWindow = window.open("", "_blank");
newWindow.document.write(htmlContent);
};
reader.readAsBinaryString(blob);
});
},
来吧,展示:(涉及隐私就不展示全了,相信兄弟们能看出来是个PDF)