pdf文件的预览以及下载
# 使用blob来进行pdf文件的预览以及下载
  # 知识点
Common_types 常见 MIME 类型列表 (opens new window)
createObjectURL (opens new window)
# 预览pdf
预览pdf可以借助iframe的src属性来传入blob文件流以达到预览的目的
- html
 
<iframe src="" id="iframe" frameborder="0"></iframe>
- js
 
function loadpdf() {
  axios({
    method: 'get',
    url:
     'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-8e76dff9-ce38-4577-9e5c-398943705060/a5b050b8-3fa1-4436-b231-7b40725de731.pdf',
    responseType: 'blob',
  }).then(function (response) {
    let blob = new Blob([response.data], { type: response.data.type })
    let url = URL.createObjectURL(blob)
    document.getElementById('iframe').src = url
  })
}
- 注意事项
 
responseType务必指定为blob
new Blob文件类型可以写为response.data.type或者参考MINE类型列表写为application/pdf
# 下载pdf
下载pdf我们借助于URL.createObjectURL()静态方法会创建一个 DOMString (opens new window)通过a标签来进行下载
  function dowanloadpdf() {
    axios({
      method: 'get',
      url:
        'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-8e76dff9-ce38-4577-9e5c-398943705060/a5b050b8-3fa1-4436-b231-7b40725de731.pdf',
      responseType: 'blob',
    }).then(function (response) {
      const link = document.createElement('a')
      let blob = new Blob([response.data], { type: response.data.type })
      let url = URL.createObjectURL(blob)
      link.href = url
      link.download = '前端工程师必备技能.pdf'
      link.click()
    })
  }