I am working a spring boot server with an angular front page. I have a service to download a .xlsx
file from my front.
Here's my code : server side code :
@GetMapping("/ExportExcel{date}")
public ResponseEntity<InputStreamResource> excelExportReport(@RequestParam Date date) throws IOException {
List<InterfaceTable> interfaceTables=interfaceTableRepo.afficheAHT(date);
ByteArrayInputStream in =ExportExcel.ahtToExcel(interfaceTables);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=customers.xlsx");
return ResponseEntity
.ok()
.headers(headers)
.body(new InputStreamResource(in));
}
Angular service:
ExportExcel(date:string){
return this.http.get<Operation[]>(this.exportUrl+date) }
The issue is that I get a HttpErrorResponse
on the angular side even though its:
error: SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:9948:51) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:3240:31) at Object`
For starters: By default, angular expects the response as
application/json
. You need to change it so you can parse it properly. For transferring files usually, it will beblob
.Then you can use any library to convert and save this blob as a file. I prefer using 'file-saver`.
The code on angular side would look like :
Spring Controller
Front-end service
Front-end component