[英]Angular download Excel is corrupted when downloading from AWS API Gateway
I'm creating an excel on the backend and return it as follows:我在后端创建一个 excel 并返回如下:
return ResponseEntity.ok()
.contentLength(export.contentLength())
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(export);
Downloading on the angular frontend as follows:在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'
});
}
This works fine when I'm running the backend on my local machine.当我在本地机器上运行后端时,这很好用。 Now the backend is deployed on AWS and it's behind a AWS API Gateway.
现在后端部署在 AWS 上,它位于 AWS API 网关后面。
When I download the excel file via the API gateway via angular the excel is corrupted.当我通过 API 网关通过 angular 下载 excel 文件时,ZBF57C906FA7D2BB656D07372E456Z 已损坏。 When I use postman it works fine.
当我使用 postman 它工作正常。
What am I doing wrong?我究竟做错了什么?
I know what is the problem bcz i encounter the same problem.我知道问题是什么,因为我遇到了同样的问题。 Aws Internally works as Linux deployment so in backend u need to change the method that is used for byte conversion.
Aws 在内部作为 Linux 部署工作,因此在后端您需要更改用于字节转换的方法。 Your frontend is fine u need to change the way in byte conversion that u used in backend.
你的前端很好,你需要改变你在后端使用的字节转换方式。
I found the problem.我发现了问题。 So Angular needs to be informed what the blob type will be.
所以 Angular 需要被告知 blob 类型是什么。 It seems that they decide based on the headers.
似乎他们根据标题做出决定。 So once I added my request headers it works fine.
因此,一旦我添加了请求标头,它就可以正常工作。 The blob is correctly transformed.
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.