Angular Http Client File Download - File name from the response

Viewed 2031

I am trying to get a File from an api url. My objective is to show this file (that was previously uploaded) in an input file field with its name. At the moment I have created the following service function:

  getDocument(): Observable<Blob> {
    const request = this.documentUrl;
    return this.http.get(request, { responseType: 'blob' });
  }

And when I use it

    this.myService.getDocument().subscribe(
      response => {
        console.log(response);
      }

I get a Blob which by definition doesn't have a name. I have seen that I can convert it into a file and give it a name but this solution doesn't fit my necessities. Is there a way I can get a File from the backend instead or is there a way to reconstruct it from the Blob with the original name it had?

1 Answers

Please make sure that the backend API sets the file name in the response header. Usually, the file name is included in content-disposition header.

For example: it looks like content-disposition: attachment;filename=XYZ.csv.

In angular, You can extract it like below:

.subscribe((response: HttpResponse<Blob>) => {
  // Extract content disposition header
  const contentDisposition = response.headers.get('content-disposition');

  // Extract the file name
  const filename = contentDisposition
        .split(';')[1]
        .split('filename')[1]
        .split('=')[1]
        .trim()
        .match(/"([^"]+)"/)[1];
});
Related