1. 程式人生 > >angular2 通過get方法請求下載二進位制的Excel檔案

angular2 通過get方法請求下載二進位制的Excel檔案

思路

  1. 獲取API資料。
  2. 使用Blob轉化為檔案物件。
  3. 建立一個a標籤並加入dom,並設定相關引數,其中Blob會轉化為連結。
  4. 觸發a標籤的 click 事件,然後銷燬a標籤。

原始碼

Service.ts

  downloadService(): any {
      let downloadUrl= `${RootUrl}/data/all`;
      return this.http.get(downloadUrl,{responseType:3})
            .map(res => {return res;});
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Component.ts

  downloadComponent(): void
{ this._listService.downloadService() .subscribe(
res=> {
//let res=res.json();可能要轉化型別
var blob = new Blob([res.json()], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); var objectUrl = URL.createObjectURL(blob); var a = document.createElement
('a'); document.body.appendChild(a); a.setAttribute('style', 'display:none'); a.setAttribute('href', objectUrl); a.setAttribute('download', 'excle檔案'); a.click(); document.body.removeChild(a); //釋放URL地址 URL.revokeObjectURL(objectUrl); } ); }
{responseType:3}報錯則換
{'responseType':'blob'}