美文网首页
vue 前端预览pdf

vue 前端预览pdf

作者: IamaStupid | 来源:发表于2020-06-18 16:46 被阅读0次

vue 前端预览pdf

情形:页面中有个table,其中有一列是显示文档名称,点击pdf文档名称,就在浏览器中打开这个pdf。

// html
<el-table-column min-width="180" show-overflow-tooltip prop="pdfFileName" label="合同文档">
          <template slot-scope="{row}">
            <el-button type="text" @click="pdfPreview(row)">{{row.pdfFileName}}</el-button>
          </template>
</el-table-column>

点击文件名称,需要调用接口下载文件,接口返回的是一序列的二进制文件,就是一大串字母数字组成的字符串。

// js
pdfPreview (row) {
      api.pdfDownload({contractId: row.contractId}).then(res => {
        const binaryData = []
        binaryData.push(res)
        // 获取blob链接
        let pdfUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
        window.open(pdfUrl)
      })
},
downloadExcel (id) {
  api.downExcel({id:id}).then(res =>{
        const blob = new Blob([res])//构造一个blob对象来处理数据
        const fileName = '列表信息.xlsx'

        //对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
        //IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) { //支持a标签download的浏览器
          this.fileUrl = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = this.fileUrl
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href) //释放url
          document.body.removeChild(link)//释放标签
        } else { //其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
  })
}

本项目使用的是axios,如果想下载文件,还需要对请求做一些配置。

// 封装axios的http.js
interceptorInstance.interceptors.request.use(config => {
      ....
      if (config.url.indexOf('/excel/Download') !== -1) {
          config.responseType = 'blob'
      }
      if (config.url.indexOf('/pdfDownload') !== -1) {
            // 一定要设置响应类型,否则预览pdf加载为空白
            config.responseType = 'arraybuffer' 
            // console.log("config.responseType = 'arraybuffer'")
      }
      ......
}

经测试chrome, ie11都可以。

注意,除了下载文件的返回数据和普通接口返回数据不同,所以一般来讲,response.use里面应该也需要过滤掉下载接口,不使用一般接口的响应逻辑。

相关文章

网友评论

      本文标题:vue 前端预览pdf

      本文链接:https://www.haomeiwen.com/subject/neosxktx.html