我在Angular2应用程序中保存xlsx有一些问题:
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=>{ });
我从后端收到的回复如下:
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
我做错的任何想法?
解决方法
问题是开箱即用不支持二进制响应内容.您需要在底层XHR对象上“手动”设置响应类型
作为一种解决方法,您需要扩展Angular2的browserXhr类,如下所述,将responseType设置为基础xhr对象上的blob:
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); } }
在提供商中注册此类时要小心,因为它是全局的.您应该只在执行请求的组件中设置它.在您的情况下,您获得响应数据的字符串表示…
@Component({ (...) providers: [ provide(browserXhr,{ useClass: CustombrowserXhr }) ] }) export class ...
然后,您需要从响应对象的_body属性获取数据.您应该正常使用,因为它是内部的,但现在没有别的办法:
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=>{ (...) });
有关详细信息,请参阅此问题: