PDF文件直接下载而不是打开的方法

316 阅读1分钟

第一种,链接后面加后缀

let link = document.createElement('a')
          link.setAttribute('href', `${data}&attname=${row.accessors[0].accessoryName}`)
          link.setAttribute('download', `${data}&attname=${row.accessors[0].accessoryName}`)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)

第二种,转化为blob的格式去下载

 axios
    .get(data, {
      responseType: 'arraybuffer'
    })
    .then((r) => {
      console.log(r)
      // const blobUrl = window.URL.createObjectURL(r.data);
      // console.log(blobUrl)
      let url = window.URL.createObjectURL(
        // type属性值将影响下载文件的类型
        new Blob([r.data], { type: 'application/pdf' })
      )
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', '23.pdf')
      document.body.appendChild(link)
      link.click()
    })