【问题标题】:Angular 4 download xls [duplicate]Angular 4下载xls [重复]
【发布时间】:2018-01-22 08:41:57
【问题描述】:

我正在尝试使用 angular 和 php 作为后端下载 excel 文件 (.xls)

我的后端已经发送了我的 excel 文件作为响应,当我检查它时,它以正确的格式返回

但我的 angular 4 将文件作为损坏的格式返回(它包含一些符号,如 ��ࡱ�;��

下面是我的角码:

服务

private headers = new Headers({
 'Content-Type': 'application/x-www-form-urlencoded'
});

downloadTemplate() {
  this.options = new RequestOptions();
  this.options.headers = this.headers;

  const params: URLSearchParams = new URLSearchParams();
  params.set('token', this.currentUser.token);
  this.options.search = params;

  return this.http.get(environment.api_host + '/template', this.options);
}

组件

template() {
  this._apiService.downloadTemplate().subscribe((response) => {
    const blob = new Blob([(<any>response)._body], {type: 'application/vnd.ms-excel'});
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'template.xls';
    document.body.appendChild(link);
    link.click();
  });
}

从我的代码中,有什么我想念的吗?

【问题讨论】:

标签: php excel angular


【解决方案1】:

如果不需要订阅,那么只需在您的服务中的downloadTemplate() 方法中使用它

  window.location.href = your_URL;

【讨论】:

    【解决方案2】:

    我正在使用 FileSaver 库从 Angular 应用程序中提供文件:http://alferov.github.io/angular-file-saver/

    这里有示例代码:

    getTemplate(): Observable<Blob> {
        this.apiService.http()
            .get(environment.api_host + '/template', { responseType: ResponseContentType.Blob })
            .map(r => r.blob())
            .subscribe(
                template => {
                    FileSaver.saveAs(new Blob([template]), "template.xml");
                },
                error => {
                    console.error(error);
                }
            );
    }
    

    重要的是您应该在您的 PHP 响应中添加标头 Content-Type: application/octet-stream。完整且有效的标题集:

    $file = fopen("/tmp/examplefile.xls", "r");
    
    array(
        'Content-Disposition' => 'attachment; filename="' . basename($filePath) . '"',
        'Content-Type' => 'application/octet-stream',
        'Content-Length' => filesize($filePath),
        'Expires' => '@0',
        'Cache-Control' => 'must-revalidate',
        'Pragma' => 'public'
    );
    

    我认为您代码中的问题是标头定义:const blob = new Blob([(&lt;any&gt;response)._body], {type: 'application/vnd.ms-excel'}); 或 http 客户端选项中的响应类型。您应该从 PHP(二进制数据)发送“八位字节/流”。在角度中从该数据创建 Blob 对象并将 Blob 对象返回给用户。就是这样。

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      相关资源
      最近更新 更多