1

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?

jarosik
  • 4,136
  • 10
  • 36
  • 53

1 Answers1

1

The problem is not on the server side. The problem is in the client code.

When you make a GET request like that, you get the data in the response object.

Instead, you need to make the browser visit the URL so a download is triggered.

There are several ways to do it, but seeing that you are using jQuery, the easiest would be:

$('#downloadButton').attr({target: '_blank', href: "/download/something.xls"});

Further info: Download File Using Javascript/jQuery

ESala
  • 6,878
  • 4
  • 34
  • 55