我的服务器上有一个端点,该端点应该返回动态生成的json文件。这是我写的:
@GetMapping(value = "/{id}/json", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ApiOperation(value = "Animal data as a json file", authorizations = {@Authorization(value = "JWT")})
public ResponseEntity<byte[]> getAnimalFile(@PathVariable("id") String id) throws JsonProcessingException {
Animal animal = animalService.getAnimal(id);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + animal.getId() + ".json").body(new ObjectMapper().writeValueAsBytes(animal));
}
@ApiOperation允许swagger生成我的客户端库时包括此操作。但是,这是ng-swagger-gen在Angular端创建的:
/**
* @param id id
* @return OK
*/
getAnimalFileUsingGET(id: string): __Observable<string> {
return this.getAnimalFileUsingGETResponse(id).pipe(
__map(_r => _r.body as string)
);
}
这是不理想的,因为我无法以这种方式下载服务器生成的文件。在我的组件中,我有一个exportJSON方法:
exportJSON(): void {
this.animalService.getAnimalFileUsingGET(this.animal.id).subscribe(content => {
console.log(content); // prints the json content but I don't have the filename
});
}
我在SO上查看了其他答案,他们说使用,window.open(SERVER_ENDPOINT_HERE)
但这不起作用,因为我的端点使用身份验证(JWT)。
有没有一种方法可以:
理想的解决方案是在服务器端进行一些更改,以使swagger生成正确的响应类型,在此我可以从服务器获取文件和文件名。
请尝试以下操作:
getAnimalFileUsingGET(id: string | number): Observable<Blob> {
return this.http.get(`/stats/export/${id}`, {responseType: 'blob'}); // Adjust your GET accordingly
}
另外,您将需要安装FileSaver.js
npm i [email protected]
最后,像这样使用它:
import { saveAs } from 'file-saver';
.
.
.
.
.
exportJSON(): void {
this.animalService.getAnimalFileUsingGET(this.animal.id).subscribe((blob: Blob) => {
saveAs(blob, 'export.json');
});
}
编辑1:为了能够访问Content-disposition
标头,您需要指示Angular Http客户端在响应中进行一些更改。
getAnimalFileUsingGET(id: string | number): Observable<HttpResponse<any>> {
return this.http.get(`/stats/export/${id}`, {observe: 'response', responseType: 'json' })
}
然后,您可以像这样订阅:
exportJSON(): void {
this.animalService.getAnimalFileUsingGET(this.animal.id).subscribe((resp: HttpResponse<Blob>) => {
console.log(resp.headers.get('content-disposition'));
// Extract filename from header
const filename = '';
saveAs(resp.body, filename);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句