經過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)
    }
  });
}
相關文章
相關標籤/搜索