Angular-SpringBoot downlod excel file HttpErrorRes

2020-05-09 08:52发布

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`

2条回答
Lonely孤独者°
2楼-- · 2020-05-09 09:25

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');
});
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-05-09 09:48

Spring Controller

 @GetMapping("/ExportExcel/{date}")
 public void excelExportReport(@RequestParam Date date, HttpServletResponse httpServletResponse) throws IOException {

           List<InterfaceTable> interfaceTables=interfaceTableRepo.afficheAHT(date);
           ByteArrayInputStream in =ExportExcel.ahtToExcel(interfaceTables);
           byte[] byteArray = new byte[in.available()];
           try {
               byteArrayInputStream.read(byteArray);
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }

           ByteArrayOutputStream out = new ByteArrayOutputStream(byteArray.length);
           out.write(byteArray, 0, byteArray.length);

           httpServletResponse.setContentType("text/csv");
           httpServletResponse.addHeader("Content-Disposition", "attachment; filename=customers.csv");

           OutputStream os;
           try {
               os = httpServletResponse.getOutputStream();
               out.writeTo(os);
               os.flush();
               os.close();
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
    }

Front-end service

return this.http.get("/ExportExcel/", this.commonRepository.getRequestOptionsForCSV(URL.BEARER)).map(res => {
          return {
              filename: 'customers.csv',
              data: res.blob()
            };
});

Front-end component

this.customerService.generateReportCsv(this.receiptReportPage.value).subscribe((results)=>{
    console.log(results);

    var url = window.URL.createObjectURL(results.data);

    var a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.setAttribute('target', 'blank');
    a.href = url;
    a.download = results.filename;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
});
查看更多
登录 后发表回答