vue + axios 文件下载

实现文件下载功能时,后台返回的为文件流时,需要通过 blob 处理文件流

首先设置 responseType 对象格式为 blob ,阻止乱码问题

获取请求返回的 response 对象中的二进制文件流转为 blob 对象

创建一个临时的 url 指向 blob 对象

最后释放这个临时的 url 对象

实现的过程,涉及到了 ie 的兼容问题,ie 浏览器不支持 a 标签属性

细节代码如下:


      axios({
        url: this.downloadPath + i.id,
        method: 'get',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        responseType: 'blob'
      }).then(res => {
        let blob = new Blob([res.data], { type: 'application/octet-stream' })
        let href = window.URL.createObjectURL(blob)
        // 兼容 ie
        if (window.navigator.msSaveBlob) {
          window.navigator.msSaveBlob(blob, i.name)
        } else {
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = href
          link.download = res.headers['filename']
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(link)
        }
      })

原文地址:https://www.cnblogs.com/sxxya/p/12156160.html