I have some issues with saving xlsx
in my Angular2 app:
this._http.get('/api/file).subscribe(success=>{
var blob = new Blob([success.json()], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var downloadUrl= window.URL.createObjectURL(blob);
window.open(downloadUrl);
}, error=>{
});
The response I receive from backend is in the following form:
PK�q�H_rels/.rels���j�0��}
�{㴃1F�^Ơ�2��l%1I,c�[��3�l
l�����H��4��R�l��·����q}*�2�������;�*��
t"�^�l;1W)�N�iD)ejuD�cKz[:}g����@:�.... etc
Any ideas where I am doing mistake?
The problem is that binary response content isn't supported out of the box. You need to "manually" set the response type on the underlying XHR object
As a workaround, you need to extend the BrowserXhr
class of Angular2 as described below to set the responseType
to blob
on the underlying xhr object:
import {Injectable} from 'angular2/core';
import {BrowserXhr} from 'angular2/http';
@Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor() {}
build(): any {
let xhr = super.build();
xhr.responseType = "blob";
return <any>(xhr);
}
}
Be careful when registering this class in providers since it's global. You should set it only within the component that execute the request. In you case, you get a string representation of response data...
@Component({
(...)
providers: [
provide(BrowserXhr, { useClass: CustomBrowserXhr })
]
})
export class ...
Then you need to get data from the _body
property of the response object. You should use normally since it's an internal one but there is no other way right now:
this._http.get('/api/file).subscribe(success => {
var blob = new Blob([success._body], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var downloadUrl= window.URL.createObjectURL(blob);
window.open(downloadUrl);
}, error=>{
(...)
});
See this question for more details:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With