之前一直在找js下载的插件,后来发现下载必须通过java后台处理,什么write(),open(),close()之类的方法。如果直接是通过<a>标签倒是简单的,直接将路径摆放在上面就可以。但是我不能这样,我需要双击下载,本质上就不是打开一个路径了,而是通过Response传入路径到后台处理数据了。
1、datagrid事件:
/*~~~~~~↓↓↓↓↓图片处理↓↓↓↓~~~~*/
$(function () {
$("#tp").datagrid({
//单击事件 查看图片
onClickRow: function (index, row) {
var imgType = row.picUrl.substr(row.picUrl.lastIndexOf(".")+1);
var imgshow = row.picUrl;
if(imgType == ‘dwg‘ || imgType == ‘dxf‘ || imgType == ‘dwt‘ || imgType == ‘dws‘ || imgType == ‘doc‘ || imgType == ‘docx‘ || imgType == ‘pdf‘){
imgshow = "http://192.168.91.162/xian/demo/components/imgupload/images/icon_file.jpg";
}
document.getElementById("myImage").src=imgshow;
},
//双击事件 下载
onDblClickRow: function (index, row) {
window.location.href = "download.htm?filePath=" + row.picUrl + "&filename="+row.picUrl;
}
});
})
2、
download.jsp
import="java.io.InputStream,java.io.OutputStream,java.net.URLEncoder,java.net.URL,java.net.URLConnection"%>
<%
String filename = request.getParameter("filename");//获取文件的相对路径
String filePath = request.getParameter("filePath");
//response.setHeader告诉浏览器以什么方式打开 //假如文件名称是中文则要使用 URLEncoder.encode()编码 //否则直接使用response.setHeader("content-disposition", "attachment;filename=" + filename);即可
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
response.setHeader("Content-Encoding", "binary");
response.setContentType("application/x-download");
URL url = new URL(filePath);
URLConnection urlconn = url.openConnection();
urlconn.setConnectTimeout(3000);
InputStream stream =urlconn.getInputStream();//获取文件的流 ,也可以这样:InputStream stream = new FileInputStream(url);
OutputStream os=response.getOutputStream();//输出流
out.clear();
out=pageContext.pushBody();
byte[] b=new byte[1024];//缓存作用
int len=0;
while((len=stream.read(b))!=-1){ //整体上就是通过路径先获取流,放置在buffer中,然后遍历输出流。
os.write(b,0,len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
}
stream.close();
%>
原文:http://www.cnblogs.com/1023linlin/p/6404837.html