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");

  }

猜你喜欢

转载自blog.csdn.net/qq_37201926/article/details/84624803
今日推荐