在Bloular2中将Blob保存为xlsx

uks*_*ksz 5 blob angular

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

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=>{

            });
Run Code Online (Sandbox Code Playgroud)

我从后端收到的回复如下:

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
Run Code Online (Sandbox Code Playgroud)

我做错的任何想法?

Thi*_*ier 5

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

作为一种解决方法,您需要扩展BrowserXhrAngular2 的类,如下所述,responseTypeblob在底层xhr对象上设置to :

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

在提供商中注册此类时要小心,因为它是全局的.您应该只在执行请求的组件中设置它.在您的情况下,您获得响应数据的字符串表示...

@Component({
  (...)
  providers: [
    provide(BrowserXhr, { useClass: CustomBrowserXhr })
  ]
})
export class ...
Run Code Online (Sandbox Code Playgroud)

然后,您需要从_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=>{
  (...)
});
Run Code Online (Sandbox Code Playgroud)

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

  • 它工作正常,但它不适用于当前的angular2版本.`_body`现在是私有的,但你可以用`success ['_ body']`来访问它. (2认同)