Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: enter image description here

Didn't show Content-Disposition !!

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

like image 780
OnnaB Avatar asked Sep 04 '25 03:09

OnnaB


2 Answers

Hope this will save your time,

First import file-saver to your components.ts file

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

'Access-Control-Expose-Headers', 'Content-Disposition'
like image 124
Mohit Savaliya Avatar answered Sep 06 '25 16:09

Mohit Savaliya


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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!