Downloading a file from a server is trivial and so is the implantation of it using httpservletresponse. But after fighting with for a long time I finally came across this jQuery plugin. This works well as long as we make HTTP request using GET or POST to server and the server responds with a file to download.
The plugin accepts 3 arguments for url, data, and method. You can pass data to these arguments just as you would to jQuery's $.post or $.get functions, and assuming the server has no problems handling the request, the front end will respond with a prompt for a file download and the user never needs to leave the page. Here's an example call to the plugin: ```javascript // the second argument can't be left blank, so if you don't need it, you can write anything $.download('get', 'file=file', 'get'); ```
and you’re done!
Of course, if the server doesn’t send the correct response, it wouldn’t work. These are the list of headers that I used for the response sent from the server.
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
// set headers
response.setContentType("application/pdf"); // Your content type
response.setHeader("Content-Disposition", "attachment; filename=somefile.pdf");