如何获得与Angular5下载的文件的名称

问题描述 投票:0回答:3

我的回答是头:

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

我想这个代码,

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

这显示在控制台:enter image description here

没有显示内容处置!

我如何从报头中的文件的名称?

angular typescript http-headers blob
3个回答
0
投票

后端需要返回一个特定的标题,Access-Control-Expose-Headers。如果不这样做,角不公开的头,解释为什么你不能看到它。

You can find more information here(虽然这是一个有点老)和even more information here


0
投票

尝试这个:

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

0
投票

其实,在角响应身体没有恢复,可能需要的所有数据。因此,我们需要指定我们需要完整的响应。要做到这一点,你需要与观察添加HTTPOptions:在服务“响应”为“体”,

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

然后你就可以得到完整的响应,通过订阅这种方法,

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

您可以参考在Angular Documentation更多细节

© www.soinside.com 2019 - 2024. All rights reserved.