I'd like to download a file async. I have a working sync method that runs when called from a url:
<a th:href="@{'download/' + ${person.number}}">download</a>
and:
@RequestMapping(value = "/download/{number}", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadFile(@PathVariable Long number) throws Exception {
byte[] array = Files.readAllBytes(file.toPath());
String fileName = "attachment; filename="+number+".xls";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("charset", "utf-8");
responseHeaders.setContentType(MediaType.valueOf("text/html"));
responseHeaders.setContentLength(array.length);
responseHeaders.set("Content-disposition", fileName);
return new ResponseEntity<byte[]>(array, responseHeaders, HttpStatus.OK);
}
Now I'd like to call it via jQuery/AJAX, so what I have is:
<button class="btn" id="downloadButton" name="23">download</button>
$('#downloadButton').click(function() {
var urlToCall = "/download/"+this.name;
$.ajax({
type:'GET',
url: urlToCall,
success: function(data){
}
});
});
This code calls my Java method and then JS success function, but a file is not downloaded. I tried with @ResponseBody but it didn't change anything. What did I miss?