I try to download a CSV file that is available under a remote URL using Ajax and jquery (I don't want to reload the view, just want to download the file).
The problem is, that file doesn't download at all, which is confusing me a bit. Here's how I call the GET endpoint that is supposed to download the file:
<script>
$("#downloadBtn").click(function() {
$.get("${pageContext.request.contextPath}/download?path="+path);
});
<script>
And here's my controller that's responsible for handling that request:
@GetMapping("/download")
public void downloadCsv(HttpServletResponse response, @RequestParam(required = true) String path) {
try {
URL url = new URL(path);
response.setHeader("Content-disposition", "attachment;filename=" + FilenameUtils.getName(url.getPath()));
response.setContentType("text/csv");
InputStream is = url.openStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ( (len = is.read(buf)) > 0 ) {
outs.write(buf, 0, len);
}
outs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The code in my controller basically refers to this SO question: How to download file from url using Spring MVC?
I'm just wondering why once the GET request is completed I can't see any file downloaded. Any ideas on this?