您的位置:首页 > Web前端 > AngularJS

angular2 通过get方法请求下载二进制的Excel文件

2017-11-22 10:20 357 查看

思路

获取API数据。使用Blob转化为文件对象。创建一个a标签并加入dom,并设置相关参数,其中Blob会转化为链接。触发a标签的 click 事件,然后销毁a标签。

源码

Service.ts
downloadService(): any {
let downloadUrl= `${RootUrl}/data/all`;
return this.http.get(downloadUrl,{responseType:3})
.map(res => {
return res;
});
}
123456Component.ts
downloadComponent(): void {
this._listService.downloadService()
.subscribe(res => {
//let res=res.json();可能要转化类型
var blob = new Blob([res.json()], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); var objectUrl = URL.createObjectURL(blob); var a = document.createElement('a'); document.body.appendChild(a); a.setAttribute('style', 'display:none'); a.setAttribute('href', objectUrl); a.setAttribute('download', 'excle文件'); a.click(); document.body.removeChild(a); //释放URL地址 URL.revokeObjectURL(objectUrl);});}
{responseType:3}报错则换{'responseType':'blob'}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: