简体   繁体   English

使用JSP / Servlet / Ajax下载文件而无需刷新页面

[英]Download file without refreshing the page using JSP/Servlet/Ajax

I have a file to dowmnload from servlet and i need to download it when user clicks download button without being page refreshed.Hiw can i achieve this. 我有一个要从servlet下载的文件,当用户单击下载按钮而不刷新页面时,我需要下载它。 Here is my jsp code.I m allowing user to dpownload the file by inputting the credentials in search box.So my file searching logic is in servlet. 这是我的jsp代码。我允许用户通过在搜索框中输入凭据来加载文件,因此我的文件搜索逻辑在servlet中。

<form action="Download_Servlet" class="download" method="post">     
Search:<input type="text" name="dropdown" id="datedropdown">
<input type="submit" id="downloadRecords" value="Download">

Here is my servlet code 这是我的servlet代码

response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=abc.csv");
ServletOutputStream out = res.getOutputStream();
for (Order traverse : orderMap.values()) 
    {   
        out.write(traverse.toString().getBytes());
        out.write("\n".getBytes());
        out.flush();
    }

Reason for using for loop is to write hundreds of records into file and then flush it..Nbow the concern is when user clicks download button page is trying to be redirect but there is no code in servlet for redirecting the response so why this is happening..I want is when download button clicked, file only should be downloaded without page being redirected. 使用for循环的原因是将数百条记录写入文件,然后刷新它。 ..我要的是单击下载按钮时,应仅下载文件,而不重定向页面。

Here's a function : 这是一个函数:

function ajax_download(url, data) {
    var $iframe,
        iframe_doc,
        iframe_html, 
        input_name;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                " style='display: none' src='about:blank'></iframe>"
               ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;

    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url +"'>" +
                  "<input type=hidden name='" + input_name + "' value='" +
                  JSON.stringify(data) +"'/></form>" +
                  "</body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

Usage : 用法:

$(document).on('click', '#download_button_id', function(){
    ajax_download('http://www.mridulahuja.com/uploads/1/3/8/6/13860206/handy_notes_v2.0.rar');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM