Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  87] [ 3]  / answers: 1 / hits: 23106  / 8 Years ago, mon, march 21, 2016, 12:00:00

I need to download file from server via ajax. The problem is that the file is not stored on server. My java-based backend automatically generates file from request parameters and returns it in response body:



  @RequestMapping(value = /download, method = RequestMethod.GET)
public void download(@RequestParam String description, @RequestParam Long logId, HttpServletResponse response) {
try {
InputStream fileContent = // getting file as byte stream
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(Content-Disposition, attachment; filename=file.zip);
ServletOutputStream responseOutputStream = response.getOutputStream();
org.apache.commons.io.IOUtils.copy(fileContent, responseOutputStream);
response.flushBuffer();
} catch (IOException e) {
logger.error(Attempt to download file failed, e);
}
}


So i need to handle it and allow user to download file.
My client side contains this:



$.ajax({
type: GET,
url: /download,
data: {
description: test,
logId: 123
},
success: function(data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = file.zip;
link.click();
}
})


Controller returns file, but then nothing happens. What am i doing wrong?


More From » java

 Answers
301

Don't make an AJAX call, but rather set the window's href to point to URL for downloading the file. Then change the content type of the response to application/x-download and set the header of the response to be Content-disposition:



response.setContentType(application/x-download);
response.setHeader(Content-disposition, attachment; filename= + fileName);
response.flushBuffer();

function download(fileName) {
window.location.href = /download?description=test&logId=123;
}


Also, have a look at this SO post which addresses a similar problem to the one you have.


[#62856] Saturday, March 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;