在Angular2中将Blob保存为xlsx [英] Saving Blob as xlsx in Angular2

查看:308
本文介绍了在Angular2中将Blob保存为xlsx的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将Angular2应用程序中保存xlsx时遇到了一些问题:

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?

推荐答案

问题是开箱即用不支持二进制响应内容.您需要手动"在基础XHR对象上设置响应类型

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

作为一种解决方法,您需要按如下所述扩展Angular2的BrowserXhr类,以在基础xhr对象上将responseType设置为blob:

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 ...

然后,您需要从响应对象的_body属性获取数据.您应该正常使用,因为它是内部的,但目前没有其他方法:

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:

这篇关于在Angular2中将Blob保存为xlsx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆