背景:碰到了在当前页面预览pdf(不打开新的窗口,采用iframe),并下载。
一、pdf的预览
1.在适合位置嵌入iframe标签
<iframe :src="pdfUrl" frameborder="0" width="100%" :style="{height: tableHeight,overflow:'auto'}"></iframe>
2.在methods中添加相应方法
pdfPreview(val) {
this.previewDownFile(val).then(v => {
if (v.status == 200) {
const binaryData = [];
binaryData.push(v.data);
let url = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
this.pdfUrl = url
} else {
this.$message.error("请求错误!");
}
})
},
previewDownFile(val) {
return new Promise((resolve, reject) => {
this.$axios({
url: `file-server/download/annex/${val.value}`,
timeout: 0,
method: 'get',
responseType: 'blob',
header: {"Content-Type": "multipart/form-data"},
}).then(res => {
resolve(res)
}).catch(() => {
resolve(false);
});
});
},
二、pdf的下载
pdfUpdate() {
this.previewDown().then(v => {
if (v.status == 200) {
if (!v) {
return;
} else {
const elink = document.createElement("a");
// console.log(new Blob([v.data]));
elink.href = window.URL.createObjectURL(new Blob([v.data], {type: `application/pdf`}));
elink.style.display = 'none';
elink.setAttribute('download', this.tabData.dataCateName);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}
}
})
},
previewDown() {
return new Promise((resolve, reject) => {
this.$axios({
url: `file-server/download/${this.emitData.fileId}`,
timeout: 0,
method: 'get',
responseType: 'blob',
header: {"Content-Type": "multipart/form-data"},
}).then(res => {
resolve(res)
}).catch(() => {
resolve(false);
});
});
},
总结:其实但看代码还是蛮简单的。但是实际操作的时候,还是费了一番功夫。