步骤如下
1.获取项目的路径
String projectPath = request.getSession().getServletContext().getRealPath("/");
2.获取tomcat服务器中的文件字节缓冲流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
3.设置下载的类型与编码
response.setContentType(request.getServletContext().getMimeType(fileName));
response.addHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
4.下载文件
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[1024*1024];
while((int count=bis.read(buffer))!=-1)
os.write(buffer,0,count);
前端:
1.form动态获取参数(修改action提交get请求)
<form onsubmit="return check(this)" action="sub.do"/>
function check(form) {
var args_ex=$("#args_exConfig").val();
form.action = form.action.split("?").length>1?form.action.split("?")[0]:form.action;
form.action = form.action + "?args_ex="+encodeURI(encodeURI(args_ex));
$("#myModal_export").modal("hide");
return true;
}
2.ajax提交(请求下载附件)
dloadAttach: function($this){
var $list = $this.find(":input:checked");
if($list.length==0){
$.alert({"title":"提示:","content":"请选择要下载的附件!"});
return;
}
var arr = new Array();
$.each($list,function(key,val){
var id = val.value;
arr.push(id);
});
var url = base + "projectInfoController/dloadAttach.do";
//var args = {"idList":JSON.stringify(arr)};
/*$.post(url,args,function(result){
$.alert("下载完成");
});*/
/*$.get(url+"?idList="+JSON.stringify(arr),function(result){
$.alert({"title":"提示:","content":"下载完成!"});
})*/
var idList = JSON.stringify(arr);
common.download(url,'post',arr);
$.alert({"title":"提示:","content":"下载完成!"});
},
// 文件下载
download: function(url, method, idList){
jQuery('<form action="'+url+'" method="'+(method||'post')+'">' + // action请求路径及推送方法
'<input type="text" name="idList" value="'+idList+'"/>' + // 文件路径
'</form>').appendTo('body').submit().remove();
},