Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

typescript - Angular-SpringBoot downlod excel file HttpErrorResponse

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`

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 be blob.

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 :

this.http.get(url,{ observe: 'response', responseType: 'blob' }).subscribe(res => { 
    const blob = new Blob([res.body], { type: 'application/vnd.ms-excel' });
    FileSaver.saveAs(blob, 'report.xls');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...