美文网首页
PDF下载(不打开)并且兼容ie

PDF下载(不打开)并且兼容ie

作者: 残_忆 | 来源:发表于2021-05-09 09:17 被阅读0次

fetch本地测试报跨域,到了线上正常

downloadPdf(href,fileName) {//下载pdf文件  href 文件地址  fileName 文件名称
        try {//如果是IE就会报错,进入catch,现在浏览器会去直接下载
          fetch(href,{//fetch现代浏览器,支持IE不支持
            headers: {
            'Content-Type': 'application/pdf'},
          }).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
            const a = document.createElement('a')
            a.href = URL.createObjectURL(blob)
            a.download = fileName+".pdf" // 下载文件的名字
            document.body.appendChild(a)
            a.click()
            URL.revokeObjectURL(a.href) // 释放URL 对象
            document.body.removeChild(a)
          })
        } catch (error) {//IE和360兼容模式会进入这里实现下载
          let a = document.createElement("a")
          document.body.appendChild(a)
          a.style.display = "none"
          a.href = href
          a.download = fileName
          a.target = "_target"
          a.click()
          document.body.removeChild(a)
          window.URL.revokeObjectURL(href)
        }
      }

相关文章

网友评论

      本文标题:PDF下载(不打开)并且兼容ie

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