1. 程式人生 > >angular點選下載檔案

angular點選下載檔案

home.component.html


<button type="button" (click)="download()">下載</button>
    

home.component.ts


downloadFile(data: any, type: number, name: string) {
    const blob = new Blob([data], {type: 'text/csv'});
    const dataURL = window.URL.createObjectURL(blob);

    // IE doesn't allow using a blob object directly as link href
    // instead it is necessary to use msSaveOrOpenBlob
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
      return;
    }

    const link = document.createElement('a');
    link.href = dataURL;
    link.download = 'export file.csv';
    link.click();

    setTimeout(() => {

      // For Firefox it is necessary to delay revoking the ObjectURL
      window.URL.revokeObjectURL(dataURL);
      }, 100);
    }
}



  download() {

    this.headers = new Headers({});
    this.headers.append('Authorization', this.storageSvc.getUserToken());
    let ActionUrl = 'xxxxxxxxxxxxxx';

    this.http.get(ActionUrl , { headers: this.headers }).subscribe(data =>
      this.downloadFile(data.text())),
      error => console.log(error ),
      () => console.info("OK");

  }