(Jhipster, front-end Angular 9 & Backend spring-boot)
My app do a xls report. The report is done with Apache Poi and copy localy.
Now I'm trying to download the file to the client side, but I don't know how.
I want to delete the file when the download is done. It's a post method because I send the data for the report.
Do you have any idea?
Here's my Controller:
public void createFullReport(@Valid @RequestBody ReportDTO report, HttpServletResponse response) throws IOException {
log.debug("REPORTDTO : {}", report);
File outputFile = this.reportService.makeFullReport(report);
log.debug("FILE EXIST:{}", outputFile.exists());
log.debug("IS FILE:{}", outputFile.isFile());
log.debug("FILE NAME:{}", outputFile.getName());
FileInputStream stream = new FileInputStream(outputFile);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + outputFile.getName());
}
My service:
create(report: IReport): any {
console.log(report);
return this.http.post<any>(this.resourceUrl, report, { observe: 'response' });
}
My component:
this.reportService.create(this.report).subscribe((response: any) => {
console.log(response);
var blob = new Blob([response._body], { type: 'application/vnd.ms-excel' });
});
EDIT
controller:
@PostMapping("/report")
@PreAuthorize(
"hasAnyAuthority(\"" +
AuthoritiesConstants.ADMIN +
"\"+\"," +
AuthoritiesConstants.CUSTOMER_ADMIN +
"\"+\"," +
AuthoritiesConstants.INSPECTOR +
"\")"
)
public ResponseEntity createFullReport(@Valid @RequestBody ReportDTO report, HttpServletResponse response) throws IOException {
log.debug("REPORTDTO : {}", report);
XSSFWorkbook wb = (XSSFWorkbook) this.reportService.makeFullReport(report);
response.setHeader("Content-Disposition","attachment; filename=\"timesheet.xlsx\"");
writeToOutputStream(response,wb);
return ResponseEntity.ok().build();
}
private void writeToOutputStream(HttpServletResponse response,XSSFWorkbook wb){
ServletOutputStream out ;
try {
out = response.getOutputStream();
wb.write(out);
wb.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Angular service:
create(report: IReport): any {
console.log(report);
let HTTPOptions:Object = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
responseType: 'blob'
}
return this.http.post<any>(this.resourceUrl, report,HTTPOptions);
}