如何从Response标头中的“ content-disposition”中获取文件名?

时间:2018-08-16 14:09:19

标签: angular typescript http-post

标题在内容处置中发送filename =“ name.xlsx”,但如何将其设置为正在下载的文件?

  

component.ts:

  public getAccordo(event: any): any {
    event.preventDefault();
    this.accordiService.getAccordo(this.filter).subscribe(
      data => {
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const anchor = document.createElement('a');
        anchor.href = window.URL.createObjectURL(blob);
      anchor.download = name

        anchor.click(); 
      },
      error => {
        console.log(error);
      }
    );
  }
  

Service.ts

getAccordo(filtro:过滤器){

return this.http.post<any>(
    `${this.ENDPOINT}/export`,

    filter,

    {responseType : 'blob' as 'json'}

);}

enter image description here

1 个答案:

答案 0 :(得分:1)

要从响应中获取headers,您需要在{observe: 'response'}中设置HttpOptions参数。

this.http.post<any>(`${this.ENDPOINT}/export`, filter, {
     responseType : 'blob' as 'json',
     observe: 'response'
})

然后在subscribe函数中,您可以通过headers属性获取标头。获取名称后,您现在可以设置文件的名称。