How to get the name of a file downloaded with Angular5

[亡魂溺海] 提交于 2019-12-08 09:50:49

问题


My response Headers is:

HTTP/1.1 200 OK
Content-Disposition: attachment; filename="file.docx"
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Thu, 26 Apr 2018 10:37:00 GMT
ETag: W/"c61-16301871843"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Length: 3169
Date: Thu, 26 Apr 2018 10:37:00 GMT
Connection: keep-alive

I tried this code,

 public download(id: string): Observable<Blob> {
    let headers = new Headers();
    const _baseUrl = (Api.getUrl(Api.URLS.download));
    headers.append('x-access-token', this.auth.getCurrentUser().token);
    headers.append('sale_id', id);
    return this.http.get(_baseUrl, { headers: headers, responseType: ResponseContentType.Blob})
      .map((res) => {
        console.log(res.headers) // show like in image
        return new Blob([res.blob()], { type: 'application/octet-stream' })
      });
  }

that show in console:

Didn't show Content-Disposition !!

How do I get the name of the file from the headers?


回答1:


Your backend needs to return a specific header, Access-Control-Expose-Headers. If you don't, Angular doesn't expose the header, explaining why you can't see it.

You can find more information here (although it's a bit old) and even more information here




回答2:


try this:

 (res: Response) => {
  const contentDisposition = res.headers.get('content-disposition') || '';
  const matches = /filename=([^;]+)/ig.exec(contentDisposition);
  const fileName = (matches[1] || 'untitled').trim();
  return fileName;
};



回答3:


Actually, The response body in angular doesn't return all the data you may need. So we need to specify that we need the full response. To do that you need to add HTTPOptions with observe: "response" as 'body' in the service,

var HTTPOptions = {
     headers: new HttpHeaders({'Accept': 'application/pdf; charset=UTF-8',}),
     observe: "response" as 'body',// to display the full response & as 'body' for type cast
     'responseType': 'blob' as 'json'
 }

 return this.http.get(url, HTTPOptions);

Then you will be able to get the complete response, By subscribing to this method,

this.service.download().subscribe((result: HttpResponse<any>) => {
 console.log(result);
 console.log(result.headers.getAll('Content-Disposition'));
}, err => {});

You can refer more details in the Angular Documentation



来源:https://stackoverflow.com/questions/50044299/how-to-get-the-name-of-a-file-downloaded-with-angular5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!