前端预览pdf功能,后端返回文件流的形式
1 首先,下载vue-pdf
npm install vue-pdf -D
2 其次,模板里面引入vue-pdf
import pdf from ‘vue-pdf’
3 html:
<pdf :src="src"></pdf>
4 相关js:
// 初始化获取pdf文件
getPdfCode (index) {
this.$set(this.loading, index, true) // iview的按钮懒加载
axios({
method: 'get',
url: process.env.VUE_APP_BASE_API + `/crm/crm/contract/preview/${this.contractID}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + this.$util.getCookie('Admin-Token')
},
responseType: 'blob' //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置!!!
}).then(res => {
this.fileStream = res
this.src = this.getObjectURL(res.data); // 将返回的数据流转换为url
this.previewContract = true
this.$set(this.loading, index, false)
})
},
// 将返回的流数据转换为url
getObjectURL(file) {
let url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {
}
} else if (window.URL != undefined) { // mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {
}
}
return url;
}
完成以上几步就可以预览pdf