使用JSP / Servlet / Ajax在不刷新页面的情况下下载文件

时间:2016-08-24 07:34:06

标签: javascript java ajax jsp

我有一个文件要从servlet下载,我需要在用户点击下载按钮时下载它而不刷新页面。我可以实现这一点。 这是我的jsp代码。我允许用户通过在搜索框中输入凭据来下载文件。所以我的文件搜索逻辑在servlet中。

<head>
<title>D3</title>
<style>
    .chart div {
        font: 10px sans-serif;
        background-color: steelblue;
        text-align: right;
        padding: 3px;
        margin: 1px;
        color: white;
    }
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

    var data = [4, 8, 15, 16, 23, 42];

    var x = d3.scaleLinear()
        .domain([0, d3.max(data)])
        .range([0, 420]);

    d3.select("body")
        .selectAll("div")
        .data(data)
    .enter().append("div")
        .style("width", function(d) { return d * 10 + "px"; })
        .text(function(d) { return d; });

</script>
</head>
<body>
</body>

这是我的servlet代码

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

使用for循环的原因是将数百条记录写入文件,然后将其刷新..注意当用户点击下载按钮页面试图重定向但是servlet中没有用于重定向响应的代码时,问题为什么这种情况正在发生。我想要的是点击下载按钮,只下载文件而不重定向页面。

1 个答案:

答案 0 :(得分:-1)

这是一个功能:

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();
}

用法:

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