Reputation: 1830
I am sending a post request to my back end to receive an Excel file. I can see in postman that my backend is sending the Excel, but in Angular, I cannot download it using the FileSaver.Js
library. Any ideas?
Here is my html markup:
<button (click)="excel()">Export Excel</button>
Here is my service class:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import * as FileSaver from 'file-saver';
import 'rxjs';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private data: DataService , private formBuilder: FormBuilder ) { }
ngOnInit() {
}
excel() {
this.data.excel().toPromise()
.then(response => this.saveToFileSystem(response));
}
private saveToFileSystem(response) {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
const parts: string[] = contentDispositionHeader.split(';');
const filename = parts[1].split('=')[1];
const blob = new Blob([response._body], { type: 'text/plain' });
FileSaver.saveAs(blob, filename);
}
}
And here is my data class method for requesting to backend:
excel() {
const headers = new HttpHeaders();
console.log("sentin")
headers.set('Content-Type', 'application/json; charset=utf-8');
return this.http.post(this.baseUrl + '/Excel', { headers: headers })
}
Upvotes: 2
Views: 7178
Reputation: 1830
Finally the answer:
I should have made these changes:
Change the method saveFileSystem
to:
private saveToFileSystem(response) {
const blob = new Blob([JSON.stringify(response.body)], { type: 'application/vnd.ms-excel;charset=utf-8' });
FileSaver.saveAs(blob, "Report.xls");
}
Add a response type to my HttpPost
like this:
{ responseType: 'text' }
Upvotes: 4