如何获取使用Angular5下载的文件的名称

时间:2018-04-26 13:29:26

标签: angular typescript http-headers blob

我的回复标题是:

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

没有显示Content-Disposition !!

如何从标题中获取文件名?

4 个答案:

答案 0 :(得分:0)

试试这个:

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

答案 1 :(得分:0)

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

You can find more information here(虽然它有点旧)和even more information here

答案 2 :(得分: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

中引用更多详细信息

答案 3 :(得分:0)

希望这可以节省您的时间,

首先将文件保护程序导入到您的components.ts文件

import { saveAs } from 'file-saver';

return this.http.get(url, { headers: {
  Accept: 'application/json',
  'Content-Type': 'application/json',
}, responseType: 'blob', observe: 'response' })
  .pipe().subscribe({
    next: (response: any) => {
      let fileName = 'file';
      const contentDisposition = response.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, '');
        }
      }
      const fileContent = response.body;
      const blob = new Blob([fileContent], { type: 'application/octet-stream' });
      saveAs(blob, fileName);
    },
    error: (error) => {
      this.handleError(error);
    }
  });

另外,将API的侧面标头设置为

'Access-Control-Expose-Headers', 'Content-Disposition'