加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Bloular2中将Blob保存为xlsx

发布时间:2020-12-17 17:39:35 所属栏目:安全 来源:网络整理
导读:我在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.crea
我在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=>{
  (...)
});

有关详细信息,请参阅此问题:

> Angular 2 download PDF from API and Display it in View

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读