Download a file from Servlet using Ajax Download a file from Servlet using Ajax ajax ajax

Download a file from Servlet using Ajax


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:


function down() {    var url = "/Jad";    var xmlhttp;    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari        xmlhttp = new XMLHttpRequest();    } else {// code for IE6, IE5        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");    }    xmlhttp.onreadystatechange = function() {        //alert("xmlhttp.status" + xmlhttp.status);        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {        }    }    xmlhttp.open("GET", url, true);    xmlhttp.send();    var elemIF = document.createElement("iframe");    elemIF.src = url;    elemIF.style.display = "none";    document.body.appendChild(elemIF);}