繁体   English   中英

Angular 下载 Excel 从 AWS API 网关下载时损坏

[英]Angular download Excel is corrupted when downloading from AWS API Gateway

我在后端创建一个 excel 并返回如下:

return ResponseEntity.ok()
        .contentLength(export.contentLength())
        .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
        .body(export);

在angular前端下载如下:

this.service.export()
.subscribe((res) => {
  const url = window.URL.createObjectURL(res);
  let a = document.createElement('a');
  document.body.appendChild(a);
  a.setAttribute('style', 'display: none');
  a.href = url;
  a.download = `export_${dateFormat(new Date(), 'dd-mm-yyyyy_HH:MM:ss')}`;
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
});


  public export(): Observable<Blob> {
    return this.http.get<Blob>(`${environment.apiUrlServer}/export`, {
      responseType: 'blob' as 'json'
    });
  }

当我在本地机器上运行后端时,这很好用。 现在后端部署在 AWS 上,它位于 AWS API 网关后面。

当我通过 API 网关通过 angular 下载 excel 文件时,ZBF57C906FA7D2BB656D07372E456Z 已损坏。 当我使用 postman 它工作正常。

我究竟做错了什么?

我知道问题是什么,因为我遇到了同样的问题。 Aws 在内部作为 Linux 部署工作,因此在后端您需要更改用于字节转换的方法。 你的前端很好,你需要改变你在后端使用的字节转换方式。

我发现了问题。 所以 Angular 需要被告知 blob 类型是什么。 似乎他们根据标题做出决定。 因此,一旦我添加了请求标头,它就可以正常工作。 blob 已正确转换。

  public export(): Observable<Blob> {
    return this.http.get<Blob>(`${environment.apiUrlServer}/export`, {
      headers: new HttpHeaders({
        'Accept':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }),
      responseType: 'blob' as 'json'
    });
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM