Downloading a file using AJAX GET from Spring Service
10,898
Don't use ajax, just set window.location.href to the url of the file and set the http content disposition header in your server script to force the browser to save the file.
function downloadFile(fileName) {
window.location.href = SERVICE_URI + "files/" + fileName;
}
Author by
charliebrownie
I am a Software Engineer with strong interest in: Clean Code and good practices the whole Software Development Process Web Development & Technologies "Life is about creating yourself." "Do what you love, love what you do."
Updated on June 07, 2022Comments
-
charliebrownie almost 2 years
I'm trying to implement a Service that automatically starts a download with the requested file.
This is my AJAX call:
function downloadFile(fileName) { $.ajax({ url : SERVICE_URI + "files/" + fileName, contentType : 'application/json', type : 'GET', success : function (data) { alert("done!"); }, error: function (error) { console.log(error); } }); }
and this is my Spring Service method GET:
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET) public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response) { try { // get your file as InputStream FileInputStream fis = new FileInputStream( fileName + ".csv" ); InputStream is = fis; // copy it to response's OutputStream ByteStreams.copy(is, response.getOutputStream()); response.setContentType("text/csv"); response.flushBuffer(); } catch (IOException ex) { throw new RuntimeException("IOError writing file to output stream"); } }
When my client requests the existing file from the server, the AJAX
success()
method is executed but the file is not even downloading. Am I doing anything wrong? -
charliebrownie over 9 yearsWhich are these headers you are talking about?
-
charliebrownie over 9 yearsWorks perfectly! Just in case someone wonders how I set the http headers in my Server:
response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
-
das almost 4 years@Musa what if my server validates the jwt token in header? Is there a way to add headers in window.location.href ? How to handle this issue?
-
Musa almost 4 yearsIf you have to set headers, then you'll have to use ajax.