通過blob(用來存儲二進制大文件)包裝ajax(或axios)請求到的data數據,實現下載EXCEL(或其他如圖片等)文件


//案例一
axios:設置返回數據格式為blob或者arraybuffer
如:
    var instance = axios.create({         ... //一些配置
        responseType: 'blob', //返回數據的格式,可選值為arraybuffer,blob,document,json,text,stream,默認值為json
    })
請求時的處理:
  getExcel().then(res => {
      //這里res.data是返回的blob對象     
      var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet這里表示xlsx類型
      var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob); //創建下載的鏈接
      downloadElement.href = href;
      downloadElement.download = 'xxx.xlsx'; //下載后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //點擊下載
      document.body.removeChild(downloadElement); //下載完成移除元素
      window.URL.revokeObjectURL(href); //釋放掉blob對象 
 })
//案例二

function createDownload(fileName, content){
    var blob = new Blob([content]);
    var link = document.createElement("a");
    link.innerHTML = fileName;
    link.download = fileName;
    link.href = URL.createObjectURL(blob);
    document.getElementsByTagName("body")[0].appendChild(link);
}
createDownload("download.txt","download file");
//案例三
function downloadExport(data) {   return axios.post(url, data).then((res)=>{     const content = res     const blob = new Blob(["\uFEFF" + content.data],{ type: "application/vnd.ms-excel;charset=utf-8"})     const fileName = '卡密.xls'     if ('download' in document.createElement('a')) { // 非IE下載       const elink = document.createElement('a')       elink.download = fileName       elink.style.display = 'none'       elink.href = URL.createObjectURL(blob)       document.body.appendChild(elink)       elink.click()       URL.revokeObjectURL(elink.href) // 釋放URL 對象       document.body.removeChild(elink)     } else { // IE10+下載       navigator.msSaveBlob(blob, fileName)     }   }); }

  

  


免責聲明!

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



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