vue 通过url下载pdf文件

1,515 阅读1分钟
<p @click="handleDoc(0)">xxx</p>
<p @click="handleDoc(1)">xxx</p>
<p @click="handleDoc(2)">xxx</p>
docObj: {
        0: 'https://xxx/xxx/xxx/xxx/xxx.doc',
        1: 'https://xxx/xxx/xxx/xxx/xxx.pdf',
        2: 'https://xxx/xxx/xxx/xxx/xxx.pdf',
      },
handleDoc (type) {
  var Url = this.docObj[type]
  if(type == 0) {
      // 下载doc文件
    window.open(Url)
  } else {
    // 下载pdf文件
    var list = Url.split('/')
    const a = document.createElement('a')
    // 这里是将url转成blob地址,
    fetch(Url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
        a.href = URL.createObjectURL(blob)
        a.download = list[list.length -1] || '' // 下载文件的名字
        document.body.appendChild(a)
        a.click()
    })
  }
},