0
votes

I'm trying to download the .csv file coming from the backend with specific filename. How can i access the filename from the api Response Header using Angular 7

enter image description here

my service (api call):

 public getDownloadFile(masterDistributorId: number, runDate: string) {
    return this.http.get
      (`${environment.apiUrl}command-center/report/download/? 
         masterDistributorId=${masterDistributorId}&runDate=${runDate}`, {
        headers: new HttpHeaders().append('Content-Type', 'application/csv'),
        responseType: 'blob',
        observe: 'response'
      }
      );
  }

my subscribe call:

 public Download(row: DistributorItem) {
    console.log(row.masterDistributorId);
    console.log(this.RunDate);
    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      console.log(res.headers);
      this.SaveFile(res);
    });
  }
1
showConfigResponse() { this.configService.getConfigResponse() // resp is of type HttpResponse<Config> .subscribe(resp => { // display its headers const keys = resp.headers.keys(); this.headers = keys.map(key => ${key}: ${resp.headers.get(key)}); // access the body directly, which is typed as Config. this.config = { ... resp.body }; }); } Visit angular.io/guide/http for more details. - Raj Kumar

1 Answers

0
votes

Get response header value: Reading the full response

key = 'content-disposition';
contentDisposition = response.headers.get(key)

Split header content disposition string: String.prototype.split()

filename = contentDisposition.split("=")[1];

Your case:

    this.CommandService.getDownloadFile(row.masterDistributorId, this.RunDate).subscribe(res => {
      let filename = res.headers.get('content-disposition').split("=")[1];
      console.log(filename);
      this.SaveFile(res);
    });