Download a file from Servlet using Ajax

2019-01-03 03:03发布

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?

3条回答
Juvenile、少年°
2楼-- · 2019-01-03 03:57

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:

查看更多
再贱就再见
3楼-- · 2019-01-03 03:58
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);
}
查看更多
Rolldiameter
4楼-- · 2019-01-03 04:05

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.

查看更多
登录 后发表回答