简体   繁体   English

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

[英]How to get the name of a file downloaded with Angular5

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 !!没有显示 Content-Disposition !!

How do I get the name of the file from the headers?如何从标题中获取文件的名称?

Your backend needs to return a specific header, Access-Control-Expose-Headers .您的后端需要返回一个特定的标头Access-Control-Expose-Headers If you don't, Angular doesn't expose the header, explaining why you can't see it.如果你不这样做,Angular 不会公开标题,解释为什么你看不到它。

You can find more information here (although it's a bit old) and even more information here 你可以在这里找到更多信息(虽然它有点旧), 甚至更多信息在这里

Hope this will save your time,希望这会节省您的时间,

First import file-saver to your components.ts file首先将文件保护程序导入到 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);
    }
  });

Also, set API side header like此外,设置 API 侧标头,如

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

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

Actually, The response body in angular doesn't return all the data you may need.实际上,angular 中的响应主体不会返回您可能需要的所有数据。 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,为此,您需要在服务中添加带有observe: "response" as 'body' 的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);

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您可以在Angular 文档中参考更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM