AJAX下载文件失败

通过ajax访问servlet来下载文件,并没有弹出下载。

 

据目前知识所限,jquery的ajax不支持下载文件。JQuery的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。

那问题就来了,既然不能使用ajax异步下载,那么想要不刷新页面而下载,需要思考一个方法。

方法一

参考:http://www.cnblogs.com/MMLoveMeMM/articles/3580368.html  

使用js创建一个form表单提交方式。

function downFile(filePath){
            var form=$("<form>");//定义一个form表单
            form.attr("style","display:none");
            form.attr("target","");
            form.attr("method","post");
            form.attr("action","../NetworkServlet?ActionId=7");
            var input1=$("<input>");
            input1.attr("type","hidden");
            input1.attr("name","JsonFileDir");
            input1.attr("value",filePath);
            $("body").append(form);//将表单放置在web中
            form.append(input1);
            form.submit();//表单提交
            form.remove();
}

后台在post中“String  mJsonFileDir = request.getParameter("JsonFileDir");”获取参数。

方法二

<tr><td><input type="button" value="查询" onclick="javascript:canSubmit('serach');" /> </td>
     <td><input type="button" value="导出Excel" onclick="javascript:canSubmit('export');" /> </td>
</tr>
<tr style="display: none;">
  <td colspan="8">
   <input type="hidden" id="expExcel" name="expExcel"  />
  </td>
</tr>
function canSubmit(type)
{
    if(type=='serach')
        document.getElementById("expExcel").value='serach';//查询
    else
        document.getElementById("expExcel").value='export';//导出
        
    Form1.submit();    
    
}

后台处理同上,根据'serach'和'export'类型判断一下而区分开。

 

posted @ 2017-07-31 15:53  小闲石  阅读(1047)  评论(0编辑  收藏  举报