I am facing some troubles with downloading files in my Angular 7 app with Spring Boot at the back end. I save files in the resource folder and encounter issues while downloading them.
@RequestMapping(value = "/getfile", method = RequestMethod.POST)
public void getFile(@RequestBody long id, HttpServletResponse response) {
try {
FileExpense fileExpense = fileExpenseRepo.findById(id).orElseThrow(() -> new CustomException(String.format("Договор (id:%s) не найден", id)));
if(fileExpense != null) {
File fileDownload = new File(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
response.setHeader("Content-Dispasition", "attachment; filename=" + fileExpense.getFileName());
response.setContentType("application/vnd.ms-excel");
OutputStream outputStream = response.getOutputStream();
Path path = Paths.get(fileExpense.getFilePath() + "/" + fileExpense.getFileName());
byte[] data = Files.readAllBytes(path);
outputStream.write(data);
outputStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
response.setStatus(500);
}
}
and angular service:
public getFile(id: number): Observable<any> {
return this.http.post('/expense/getfile', id);
}
and download function in component:
downloadFile(fileJson: FileExpenseJson){
this.expenseService.getFile(fileJson.id).subscribe(data => {
let blob = new Blob([data.blob], {type: 'application/vnd.ms-excel'});
let url = window.URL.createObjectURL(blob);
let filename = fileJson.fileName;
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
let a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
window.URL.revokeObjectURL(url);
});
}
this gives me error: message: "Unexpected token P in JSON at position 0" Please help . thanx anyway)