簡體   English   中英

在 Angular 5 中通過 blob 下載時設置文件名

[英]Set File Name while downloading via blob in Angular 5

下面是我從 API 下載文件的打字稿代碼

DownloadLM() {
var ID= sessionStorage.getItem("UserID");
    return this.http.get(this.baseurl + 'api/DownloadFiles/DownloadLM/' + ID,
      {
        headers: {
          'Content-Type': 'application/json'
        },
        responseType: 'arraybuffer'
      }
    )
      .subscribe(respData => {
        this.downLoad(respData, this.type);
      }, error => {
      });
  }

  downLoad(data: any, type: string) {
    var blob = new Blob([data], { type: type.toString() });
    var url = window.URL.createObjectURL(blob);
    var pwa = window.open(url);
    if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
      alert('Please disable your Pop-up blocker and try again.');
    }
  }

這很好下載 Excel 文件,但它為我不想要的文件提供了一個隨機名稱,我想在下載時設置我選擇的文件名,

我在哪里可以在這里設置文件名? Blob 的任何屬性?

您可以將下載屬性設置為您想要的文件名,將 href 設置為對象 url,然后只需調用 click

var blob = new Blob([data], { type: type.toString() });
var url = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = url;
anchor.click();

如果您想要上傳文件的確切文件名,請從支持的 API 流中設置文件名的自定義標頭。

您可以像這樣使用它:我的 Excel API 響應標頭:

content-disposition: inline;filename="salesReport.xls" 
content-type: application/octet-stream 
date: Wed, 22 Aug 2018 06:47:28 GMT 
expires: 0 
file-name: salesReport.xls 
pragma: no-cache 
transfer-encoding: chunked 
x-application-context: application:8080 
x-content-type-options: nosniff 
x-xss-protection: 1; mode=block

服務.ts

excel(data: any) {
  return this.httpClient.post(this.config.domain + 
  `/api/registration/excel/download`,data, {observe: 'response', responseType: 'blob'})
  .map((res) => {
      let data = {
                     image: new Blob([res.body], {type: res.headers.get('Content-Type')}),
                     filename: res.headers.get('File-Name')
                  }
    return data ;
  }).catch((err) => {
    return Observable.throw(err);
  });
}

組件.ts

excelDownload (data) {
   this.registration.excel(data).subscribe(
    (res) => {
     const element = document.createElement('a');
      element.href = URL.createObjectURL(res.image);
      element.download = res.filename;
      document.body.appendChild(element);
      element.click();
     this.toastr.success("Excel generated  successfully");
    },
  (error) =>{
     this.toastr.error('Data Not Found');
  });
}

由於有些人要求提供帶有 promise 的版本,因此您可以使用 await 和 async:

第 1 部分:從服務器獲取 Blob:

  generateSapExcel(data: GenerateSapExport): Promise<HttpResponse<Blob>> {
    return this.http.post(`${this.pathprefix}/GenerateSapExcel`, data, { responseType: 'blob', observe: 'response' })
      .toPromise()
      .catch((error) => this.handleError(error));
  }

第 2 部分:提取 HttpResponse 並將其交付給用戶:

public downloadFile(data: HttpResponse<Blob>) {
    const contentDisposition = data.headers.get('content-disposition');
    const filename = this.getFilenameFromContentDisposition(contentDisposition);
    const blob = data.body;
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.download = filename;
    anchor.href = url;
    anchor.click();
  }

  private getFilenameFromContentDisposition(contentDisposition: string): string {
    const regex = /filename=(?<filename>[^,;]+);/g;
    const match = regex.exec(contentDisposition);
    const filename = match.groups.filename;
    return filename;
  }

第 3 部分:結合兩者:

      const blobresponse = await this.dataService.generateSapExcel(dataToSend);
      this.downloadService.downloadFile(blobresponse);

第 4 部分:服務器:

        [HttpPost]
        [Route(nameof(GenerateSapExcel))]
        public async Task<FileStreamResult> GenerateSapExcel(GenerateSapExportDto dto)
        {
            Stream stream = await _sapKurepoService.GenerateSapExcel(dto);
            FileStreamResult result = File(stream, FileHelper.ContentypeExcel, "excel.xlsx");
            return result;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM