I'm trying to download a file on the click of a button in Angular. The file that gets downloaded but is 0 KB in size and does not open.
This is the code that I have so far in Angular and Spring MVC
Angular :
public downloadFile(fileName:string){
console.log("ready to download");
let param:any = {'messageId':this.loadedMessageService.messageId, 'attachmentName':fileName}
this.http.get(`https://fakeurl.com/abc/getFile`,{params:param,responseType:'blob'}).subscribe(
(data) => {
let b:Blob = new Blob([data])
//,{type: 'application/octet-stream',}
// const fileName :string= "RL.xlsx"
var url = window.URL.createObjectURL(b);
const a : HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;
// const a = document.createElement('a');
document.body.appendChild(a);
a.href = url;
a.download = fileName;
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
)
}
Spring MVC :
@GetMapping(value = "/getFile")
public @ResponseBody byte[] getFile() throws IOException {
try {
return messageAttachmentService.getFile(Integer.parseInt(request.getParameter("messageId")), request.getParameter("attachmentName"));
} catch (NumberFormatException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.error(sw.toString());
}
return null;
}
Right now when I click the button, the file gets downloaded but it's 0 KB in size and does not open. I was using type as application/octet-stream before since the file to be downloaded could be either a PDF or text file or xls. I referred to other questions too and tried changing the response type to arraybuffer. That didn't solve the issue either. What is wrong with my code?