通过Response下载。

之前一直在找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();
%>

 

 

当路径中出现中文会有FileNotFoundException,将其中的中文部分(一般是fileName)单独拿出来处理,不能将其他英文什么的一起处理,会有问题。

int separ=filePath.lastIndexOf("/");
String url_en=URLEncoder.encode(filePath.substring(separ+1),"utf-8");
System.out.println(filePath.substring(0,separ+1)+url_en);

URL url = new URL(filePath.substring(0,separ+1)+url_en);

 

 

火狐浏览器下载文件名中文乱码问题:

String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8"); // name.getBytes("UTF-8")处理safari的乱码问题
filename = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码

response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", filename));

转载于:https://www.cnblogs.com/1023linlin/p/6404837.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值