使用axios下載excel文件解決亂碼問題

1. 須將axios 配置中的responseType設置爲arraybuffer,這樣就不會讓表格出現亂碼現象; 2. 若是要動態設置文件名則須要讓後臺將名字設置到響應頭中,不然將是一個亂碼的文件名; 3. 而後經過<a></a> 標籤的特性來自動點擊下載文件; 4. 若是要兼容IE則須要利用navigator.msSaveOrOpenBlob方法; 5. 兼容Firefox 須將<a></a> 標籤添加到body中,最後再移除<a></a> 標籤javascript

例子:html

// 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的我的博客 參考鏈接vue

原文出處:https://www.cnblogs.com/gaoguowen/p/11270308.htmljava

相關文章
相關標籤/搜索