Download a file from Servlet using Ajax

I have created a zip file in my servlet. Now I would like to trigger that servlet using Ajax and prompt the download dialog to the user. I can trigger the servlet, but I don't know how to get the save dialog. How can I achieve this?


You can't "download a file using AJAX". AJAX is about downloading data from a server for JavaScript to process.

To let the user download the file either use a simple link to the file/servlet, or if you really, really need to use JavaScript, then assign the URL to document.location.href.

Also you need to make sure that the server (or in this case the servlet) sends the appropriate MIME type, in case of a ZIP file most likely application/zip.


You can't use Ajax for this. You basically want to let the enduser save the file content to the local disk file system, not to assign the file content to a JavaScript variable where it can't do anything with it. JavaScript has for obvious security reasons no facilities to programmatically trigger the Save As dialog whereby the file content is provided from an arbitrary JavaScript variable.

Just have a plain vanilla link point to the servlet URL and let the servlet set the HTTP Content-Disposition header to attachment. It's specifically this header which will force the browser to pop a Save As dialog. The underlying page will stay same and not get refreshed or so, achieving the same experience as with Ajax.

Basically:

<a href="fileservlet/somefilename.zip">download file</a>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...

    response.setHeader("Content-Type", getServletContext().getMimeType(fileName));
    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");

    // ...
}

That could also be done in JavaScript as below without firing a whole Ajax call:

window.location = "fileservlet/somefilename.zip";

Alternatively, if you're actually using POST for this, then use a (hidden) synchronous POST form referring the servlet's URL and let JavaScript perform a form.submit() on it.

See also:

  • Simplest way to serve static data from outside the application server in a Java web application
  • Abstract template for a static resource servlet