簡體   English   中英

如何獲取使用 Angular5 下載的文件的名稱

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

我的回應標題是:

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

在控制台中顯示: 在此處輸入圖片說明

沒有顯示 Content-Disposition !!

如何從標題中獲取文件的名稱?

您的后端需要返回一個特定的標頭Access-Control-Expose-Headers 如果你不這樣做,Angular 不會公開標題,解釋為什么你看不到它。

你可以在這里找到更多信息(雖然它有點舊), 甚至更多信息在這里

希望這會節省您的時間,

首先將文件保護程序導入到 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'

嘗試這個:

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

實際上,angular 中的響應主體不會返回您可能需要的所有數據。 所以我們需要指定我們需要完整的響應。 為此,您需要在服務中添加帶有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);

然后你將能夠得到完整的響應,通過訂閱這個方法,

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

您可以在Angular 文檔中參考更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM