Reputation: 1050
How do I download Excel file with as is filename returned by the service in my Angular
application? I'm using file-saver
library. Here is my code:
let blob = new Blob([response], {type: 'application/vnd.openxmlformat-officedocument.spreadsheetml.sheet;'});
saveAs(blob, 'hello.xlsx');
This is the response of Angular service:
return this.http.get(`${this.reportsUrl}`, { responseType: 'blob'});
Response of my backend service (Spring MVC). excelCreatedResource
is of type org.springframework.core.io.Resource
:
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + excelCreateResource.getFilename() + "\"")
.body(excelCreateResource);
I don't want to supply hello.xlsx
. Instead, I would just like to download the file without changing the filename returned by the service. If I access the URL directly from browser, I am able to download the Excel file.
Upvotes: 2
Views: 5278
Reputation: 745
You can save a File constructor without specifying a filename. The File itself already contains a name.
let blob = new Blob([response], {type: 'application/vnd.openxmlformatofficedocument.spreadsheetml.sheet;'});
saveAs(blob);
or you have to fetch the headers from your response , save the filename in variable and pass the variable to saveAs() function.
Upvotes: 1
Reputation: 986
Using library FileSaverJs
let wbout = <write output> // write table or json to excell
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i < s.length; i++) {
view[i] = s.charCodeAt(i) & 0xFF;
}
return buf;
}
// Save it as test.xlsx
saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}), 'hello.xlsx');
Upvotes: 1
Reputation: 4895
As per your question I think you need to observe complete response and get the header details from it. In Angular you can do this by using
let observable$ = this.http.get(`${this.reportsUrl}`, { observe: 'response'});
observable$.subscribe(response => {
let blobObj = response.body; // this should be your blob object (body of response)
let headers = response.Headers //This is a disctionary/HashMap were you'll find the content-desposition header
//.....
})
Upvotes: 2
Reputation: 978
If excelCreateResource.getFilename();
return a filename then, you can store file name in a local variable and pass this variable in saveAs()
method like:
var filename = excelCreateResource.getFilename();
saveAs(blob, filename );
Maybe it will work for you.
Upvotes: 1