簡體   English   中英

Angular 文件下載,名稱來自內容 Content-Disposition

[英]Angular file download with name from content Content-Disposition

我想使用 angular 下載生成的 xls 文件,並根據響應 header Content-Disposition 設置文件名。

我使用類似的東西

downloadFile(): Observable<any> {
  var url= "http://somehting";
  return this.http.get(url, { observe: 'response', responseType: 'blob' as 'json' });  
}

后來在我的 controller 中:

this.dataService.downloadFile().subscribe(
    data => {
        this.debug.msg("response:", JSON.stringify(data));
        saveAs(data.body, "test.xlsx");
    },
    err => {
        console.error(err);
        alert("Problem while downloading the file.\n" + "[" + err.status + "] " + err.statusText);
    }
);

不幸的是,響應頭沒有設置,正文也是空的。

response: {
   "headers":{
      "normalizedNames":{

      },
      "lazyUpdate":null
   },
   "status":200,
   "statusText":"OK",
   "url":"http://localhost:4200/MyEndpoint/GetDownload",
   "ok":true,
   "type":4,
   "body":{

   }
}

如果我將過程更改為 responseType: blob,那么我可以獲取文件的內容,但我不知道如何獲取response.headers 我錯過了什么嗎?如果是這樣,那是什么?

基於其他堆棧溢出帖子...這對我有用

在服務器上設置 header

Response.Headers.Add("Access-Control-Expose-Headers", "content-disposition");

angular dataService 定義下載程序。 重要的是設置可觀察到 HttpResponse

  downloadFile(): Observable<HttpResponse<Blob>> {

    var url =  "http://host/GetDownload";

    return this.http.get<Blob>(url, { observe: 'response', responseType: 'blob' as 'json' });
  }

和 controller

 this.dataService.downloadFile().subscribe(
      data => {

        var fileName = "report.xlsx";
        const contentDisposition = data.headers.get('Content-Disposition');
        if (contentDisposition) {
          const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = fileNameRegex.exec(contentDisposition);
          if (matches != null && matches[1]) {
            fileName = matches[1].replace(/['"]/g, '');
          }
        }

        saveAs(data.body, fileName);
      },
      err => {
        console.error(err);
        this.blockUI.stop();
        alert("Problem while downloading the file.\n"+
            "["+err.status+"] "+err.statusText);
      });
}

暫無
暫無

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

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