【问题标题】:Angular file download with name from content Content-Disposition从内容 Content-Disposition 下载带有名称的 Angular 文件
【发布时间】:2020-05-11 15:36:27
【问题描述】:

我想使用 Angular 下载生成的 xls 文件,并根据响应头 Content-Disposition 设置文件名。

我使用类似的东西

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

后来在我的控制器中:

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。 我错过了什么吗?如果是这样,那是什么?

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    基于其他堆栈溢出帖子...这对我有用

    在服务器上设置标题

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

    angular dataService 定义下载程序。重要的是将 observable 设置为 HttpResponse

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

    和控制器

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

    【讨论】:

    • 嗨!请告诉我 saveAs 功能是做什么的?
    • 据我所知,saveAs 函数是一个用于下载文件的库。
    • import { saveAs } from 'file-saver'; - github.com/eligrey/FileSaver.js
    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多