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

Angular download Excel is corrupted when downloading from AWS API Gateway

我正在后端创建一个 excel 并且 return 如下:

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 文件时,excel 已损坏。当我使用邮递员时它工作正常。

我做错了什么?

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

我发现了问题。所以 Angular 需要被告知 blob 类型是什么。看来他们是根据headers来决定的。所以一旦我添加了我的请求 headers 它就可以正常工作。 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'
    });
  }