使用axios下载excel文件解决乱码问题

1. 须将axios 配置中的responseType设置为arraybuffer,这样就不会让表格出现乱码现象;
2. 如果要动态设置文件名则需要让后台将名字设置到响应头中,否则将是一个乱码的文件名;
3. 然后通过<a></a> 标签的特性来自动点击下载文件;
4. 如果要兼容IE则需要利用navigator.msSaveOrOpenBlob方法;
5. 兼容Firefox 须将<a></a> 标签添加到body中,最后再移除<a></a> 标签

例子:

// axios config
 config = {
     responseType: 'arraybuffer'
    }

// 返回数据处理
getUserInfoExport(data).then(({data,headers}) => {
        let blob = new Blob([data], { type: 'application/vnd.ms-excel' }) // 将服务端返回的文件流(二进制)excel文件转化为blob
        let fileName = headers.filename

        if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
          window.navigator.msSaveOrOpenBlob(blob, fileName)
        } else {
          let objectUrl = (window.URL || window.webkitURL).createObjectURL(blob)
          let downFile = document.createElement('a')
          downFile.style.display = 'none'
          downFile.href = objectUrl
          downFile.download = fileName // 下载后文件名
          document.body.appendChild(downFile)
          downFile.click()
          document.body.removeChild(downFile) // 下载完成移除元素
          // window.location.href = objectUrl
          window.URL.revokeObjectURL(objectUrl)   // 只要映射存在,Blob就不能进行垃圾回收,因此一旦不再需要引用,就必须小心撤销URL,释放掉blob对象。
        }
      })

Owen的个人博客
参考连接

posted @ 2019-07-30 15:29  G_Owen  阅读(4228)  评论(0编辑  收藏  举报