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`
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();
});