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