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



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

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

在角度前端下载如下:

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部署工作,因此在后端u需要更改用于字节转换的方法。你的前端很好,你需要改变你在后端使用的字节转换方式。

我发现了问题。所以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'
});
}

最新更新