Angular使用HTTP POST下載流文件

Angular / Vue HTTP POST下載流文件
HTTP POST 請求流文件轉成excel

在使用Angular開發項目時,一般會有下載文件的功能項。通常是後臺返回下載地址,經過<a>標題或者使用window打開下載地址新窗口,瀏覽器則會識別出流文件進行文件下載。javascript

可是,有時候進行http異步請求,後臺返回的並非下載地址,而是直接返回一個文件流,這時如何使用http請求回來的文件流轉換成文件下載?java

其實並不是Angular框架存地這樣的狀況,其餘PWA如Vue,React甚至Jquery都經過http xhr進行請求而獲取的流文件,瀏覽器也並不會自動識別並自動下載。json

那固然,確定有解決方案。
方案思路:瀏覽器

  • http請求使用blob的返回類型,
  • 獲取文件流後,對數據進行Blob
  • 再提交給瀏覽器進行識別下載。

下面是代碼示例app

/**
 * 導出excel
 */
exportExcel(){
  const params = {}; // body的參數
  const queryParams = undefined; // url query的參數
  this.http.post(this.exportUrl, params, queryParams, {
    responseType: "blob",
    headers: new HttpHeaders().append("Content-Type", "application/json")
  }).subscribe(resp=>{
    // resp: 文件流
    this.downloadFile(resp);
  })
}

/**
 * 建立blob對象,並利用瀏覽器打開url進行下載
 * @param data 文件流數據
 */
downloadFile(data) {
  // 下載類型 xls
  const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  // 下載類型:csv
  const contentType2 = 'text/csv';
  const blob = new Blob([data], { type: contentType });
  const url = window.URL.createObjectURL(blob);
  // 打開新窗口方式進行下載
  // window.open(url); 

  // 以動態建立a標籤進行下載
  const a = document.createElement('a');
  const fileName = this.datePipe.transform(new Date(), 'yyyyMMdd');
  a.href = url;
  // a.download = fileName;
  a.download = fileName + '.xlsx';
  a.click();
  window.URL.revokeObjectURL(url);
}
相關文章
相關標籤/搜索