Saving Blob as xlsx in Angular2

*爱你&永不变心* 提交于 2019-12-10 14:32:07

问题


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?


回答1:


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:

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


来源:https://stackoverflow.com/questions/36769419/saving-blob-as-xlsx-in-angular2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!