pdf文件流,下载正常,但是预览全是空白页
遇到问题: 后端返回pdf文件流能下载成功,页数也是正常的,打开也是正常的。但是直接在网页上预览,页数正常但页面都是空白的。如图:
问题代码如下:
let data = JSON.stringify({ url: row.fileUrl });
wordToPdf(data).then((res) => { //wordToPdf为封装的axios请求,res为后端返回的文件流
let pdfFile = window.URL.createObjectURL(
new Blob([res], {
type: "application/pdf;charset=utf-8",
})
);
window.open(pdfFile);
});
解决办法: 需要添加请求类型responseType: 'blob'
,所以不用封装的axios
,使用原生的axios
。这样就能正常预览了。代码如下:
const baseURL = process.env.VUE_APP_BASE_API;
import axios from "axios";
let data = JSON.stringify({ url: row.fileUrl });
axios({
method: "POST",
url: baseURL + `/system/report/file/onlinePreview`,
data: data,
responseType: "blob", // 必须更改responseType类型为 blob
})
.then((res) => {
console.log(res);
let pdfFile = new Blob([res.data], {
type: "application/pdf;charset=utf-8",
});
let url = window.URL.createObjectURL(pdfFile);
window.open(url);
})
.catch((err) => {
console.log(err);
});
预览正常了
下载方法(自用)
/** 下载按钮操作 */
handleDownload(row) {
fetch(row.fileUrl)
.then((res) => res.blob())
.then((blob) => {
const a = document.createElement("a");
const objectUrl = window.URL.createObjectURL(blob);
a.download = row.fileName;
a.href = objectUrl;
a.click();
});
},