使用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的個人博客
參考連接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM