1

Following is my Response header for POSTMAN request:

Content-Disposition: attachment; filename="file_name.docx.docx"

where file_name is the actual file name

Now, while downloading the file in Angular, I want this exact name. But instead of that, every time I download the file it picks up some random name

Following is my angular code:

this.http.get("url", {responseType: 'blob'}).subscribe((res) => {
  const blob = new Blob([res], {type: 'application/msword'});
  const url = window.URL.createObjectURL(blob);
  window.open(url);
})

Is there any I can get the exact name of the file which we want to download, i.e. the same name which I am getting in Postman request header

Frank Fajardo
  • 7,034
  • 1
  • 29
  • 47
Safwan Bardolia
  • 569
  • 1
  • 4
  • 12
  • You're already subscribing to this.http.get(). Try accessing the `.headerProperty`this: https://stackoverflow.com/a/50135330/421195 – paulsm4 Sep 05 '22 at 06:14

1 Answers1

0

Could you try this below method using observe and see if it fixes the issue?

ts

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .get(
        'https://www.mtsac.edu/webdesign/accessible-docs/word/example03.docx',
        {
          responseType: 'blob' as 'json',
          observe: 'response' as 'body',
        }
      )
      .subscribe(async (res: any) => {
        console.log(res);
        const filename = res.headers.get('filename') || 'test.docx';
        const blob = res.body;
        const blobFinal = new Blob([blob as Blob], {
          type: 'application/msword',
        });
        const url = window.URL.createObjectURL(blobFinal);
        console.log(url);
        var fileLink = document.createElement('a');
        fileLink.href = url;
        fileLink.download = filename;
        fileLink.click();
      });
  }
}

forked stackblitz

Naren Murali
  • 19,250
  • 3
  • 27
  • 54