pdf 地址 实现在线预览

444 阅读1分钟

如果pdfUrl 返回的是blob文件流的形式,用window.open(pdfUrl)时候会下载,不能预览,

考虑用const url = URL.createObjectURL(blob)返回的url,window.open(url)

1. 步骤:

  • 设置点击事件
function openPdf (url) {
  window.open(`../../../src/views/preView/viewer.html?fileUrl=${url}`)
}
  • 项目根目录(可以是其它目录)下添加html文件,内容如下:
<html>
  <body>
    <script type="module">
      import axios from 'axios'
      import { getUrlParam } from '@/utils/index.js'
      const urlStr = getUrlParam('fileUrl')
      if (!urlStr) return
      axios({
        methods: 'POST',
        url: urlStr,
        responseType: 'blob'
      }).then((res) => {
        var blob = new Blob([res.data], {
          type: 'application/pdf;chartset=UTF-8' //指定下载的类型
        })
        let fileURL = URL.createObjectURL(blob)
        window.open(fileURL)
      })
    </script>
  </body>
</html>

也可以直接在框架中写html中的内容

2. 该地址是blob下载可指定的类型(type)