zoukankan      html  css  js  c++  java
  • 使用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的个人博客
    参考连接

  • 相关阅读:
    监控kubernetes集群的方式
    Prometheus的集群与高可用
    Grafana简单用法
    Prometheus实战之配置汇总
    Leetcode Surrounded Regions
    leetcode Spiral Matrix II
    leetcode Regular Expression Matching
    leetcode Set Matrix Zeroes
    leetcode 较难题II
    Leetcode 数独
  • 原文地址:https://www.cnblogs.com/gaoguowen/p/11270308.html
Copyright © 2011-2022 走看看