1.pdf下载
首先说下下载问题,
-
通过文件地址下载 存留问题 无法下载
试过a标签搭配文件地址下载,最后发现行不通,一点击下载就直接打开了,不符合需求。 -
通过文件流形式,完美解决,
这里通过后端把文件转换文件流的格式传给前端,前端再去转换下载,就OK了
第一步,请求接口
// pd下载
export const getDownloadFile = data =>{
return request({
url:"/contract/downloadFile",
method:"post",
data,
responseType: 'arraybuffer' // 中重点格式,否则下载的会空白。
})
}
//html
<span @click="downloadPDF"> 下载 </span>
// js
import {
getDownloadFile,
} from "@/request/orderApi.js"
methods:{
// 下载
async downloadPDF(){
await getDownloadFile({
"orderNo": this.interForm.orderNo,
}).then(res=>{
let setData = res.data;
const blob = new Blob([setData], {
type: 'application/pdf;chartset=UTF-8'
})
let filename = '贸易合同.pdf'
// 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
const elink = document.createElement('a')
elink.download = filename
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href) // 释放URL 对象
document.body.removeChild(elink)
}).catch(err=>{
console.log('err',err)
})
},
}
PDF预览
网上有对应插件,vuepdf,和jspdf等插件,可供选择,不想爬坑了。。。
我这边是用的iframe实现预览的,
1.自定义预览组件。
previewPdf.vue
<template>
<el-dialog :visible.sync="dialogVisible" width="90%" top="0" height="100%" :before-close="handleClose">
<!-- <object width="100%" height="800px" :data="contractURL"></object> -->
<iframe width="100%" height="800px" :src="contractURL" frameborder="0"></iframe>
</el-dialog>
</template>
<script>
export default {
props: {
URL: {
type: String,
default: ''
}
},
watch: {
URL(val) {
this.contractURL = val
// console.log(val,'val')
}
},
data() {
return {
dialogVisible: false,
contractURL: ''
}
},
mounted() {
// console.log('this.URL',this.URL)
},
methods: {
handleClose() {
this.dialogVisible = false
this.contractURL = ''
},
openPDF(val) {
this.contractURL = val
console.log(this.contractURL, 'ziji1')
this.dialogVisible = true
}
}
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog {
background: none;
}
::v-deep .el-dialog__close {
color: #fff;
font-size: 35px;
border: solid 2px #fff;
border-radius: 50%;
position: absolute;
}
</style>
页面调用
// 1. 引入组件,
<div>
<PreviewPDF :URL="contractURL" ref="pdf" />
</div>
import PreviewPDF from "@/components/previewPdf.vue"
components:{
PreviewPDF,
},
methodsP:{
// 查看pdf
LooKPDF(){
this.$refs.pdf.openPDF(this.contractURL); //通过ref传合同地址。
},
}