angular發送post請求,下載文件

downloadFile(data, type) {
    this.downloadInfo.tid = data.id;
    if (data.savedReports.length !== 0) {
      data.savedReports.map(item => {
        this.downloadInfo.rid = item.id;
      });
    }
    this.downloadInfo.type = type;
    this.listService.download(this.downloadInfo, { responseType: 'blob', observe: 'response' }).subscribe({
      next: (response: any) => {
        this.downloadFileBlob(response);
      },
      error: (error: any) => {
        this.message.error(error);
      },
      complete: () => {
        console.log('compolete');
      }
    });
  }


downloadFileBlob(data: any) {
    const blob = new Blob([data.body], { type: 'text/csv' });
    const link = document.createElement('a');
    console.log(window.URL.createObjectURL(data.body));
    link.setAttribute('href', window.URL.createObjectURL(data.body));
    link.setAttribute('download', fileName);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    const dataURL = window.URL.createObjectURL(blob);
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob);
      return;
    }
    setTimeout(() => {
      // For Firefox it is necessary to delay revoking the ObjectURL
      window.URL.revokeObjectURL(dataURL);
    }, 100);
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章