0

My app suppose to download file from DB.

Controller:

@GetMapping(value = "/download/{id}")
public ResponseEntity<Resource> downloadBook(@PathVariable Long id) {

Book book = bookService.findById(id);

return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + book.getFileName() + ".pdf\"")
        .body(new ByteArrayResource(book.getFile()));

}

This works when i call it directly from browser (download pop up), but what i'm tring to do is handle it with ajax call. This is my ajax method so far, but this code actually just alert me with success with no dowload pop up.

downloadBook : function(bookId) {
    $.ajax({
        url : basePath + '/book/download/' + bookId,
        success : function() {
            alert("success!");
        },
        error : function() {
            alert("error!");
        }
    });
}
StefanTflch
  • 145
  • 2
  • 14

2 Answers2

1

See Download a file by jQuery.Ajax

What's happening here is that your ajax request is being made to /book/download/ as specified in the url: parameter. When the request completes successfully it fires the success callback. However, all you are doing there is showing an alert - with alert("success!") - so nothing further will happen.

The linked answer explains why you cannot simply do this with ajax like you might imagine. I haven't reiterated all of the linked answer as it's already been explained there, but the principal of that answer is exactly the same for your problem.

Andy
  • 5,142
  • 11
  • 58
  • 131
0
downloadBook : function(bookId) {
    window.location = basePath + '/book/download/' + bookId
}

My downloadBook method looks like this now and it solved my problem.

StefanTflch
  • 145
  • 2
  • 14