页面超链接下载

代码段:

fileName = filePath.substring(filePath.lastIndexOf("/")+1);

f=new File(localPath+"/"+fileName);

in = new FileInputStream(f);

fileByte = new byte[in.available()];

in.read(fileByte);

fileName =URLEncoder.encode(fileName, "UTF-8").replace("+","%20");

String agent = request.getHeader("USER-AGENT");

if(agent != null && agent.contains("Firefox")) {// FF   

  fileName = "*=UTF-8''"+fileName;   

}else{

  fileName="="+fileName;

}

response.reset();

response.addHeader("Content-Disposition", "attachment; filename" + fileName);

response.setContentType("application/octet-stream; charset=utf-8");

out= response.getOutputStream();

out.write(fileByte);

要下载只需获取OutputStream write就可,但这没有文件名和文件扩展名

需要response.addHeader();

Content-Disposition: attachment; filename=文件名字.doc

但文件名会出现乱码,在IE和谷歌浏览器下把文件名转成 %-escaped-hexadecimal,

 Content-Disposition: attachment; filename="%d0%a2%d0%b5%d0%ba%d1%81%d1%82%d0%be%d0%b2%d1%8b%d0%b9 %d0%b4%d0%be%d0%ba%d1%83%d0%bc%d0%b5%d0%bd%d1%82 %d0%b4%d0%be%d0%ba.doc"

fileName =URLEncoder.encode(fileName, "UTF-8").replace("+","%20");

这样文件名就ok了,不幸的是火狐不支持,需要加入火狐特定的解决方案

Content-Disposition: attachment;filename*=utf-8''%d0%a2%d0%b5%d0%ba%d1%81%d1%82%d0%be%d0%b2%d1%8b%d0%b9%20%d0%b4%d0%be%d0%ba%d1%83%d0%bc%d0%b5%d0%bd%d1%82%20%d0%b4%d0%be%d0%ba.doc

判断是否是火狐浏览器:

String agent = request.getHeader("USER-AGENT");

if(agent != null && agent.contains("Firefox")) {// FF   

  fileName = "*=UTF-8''"+fileName;   

}else{

  fileName="="+fileName;

}

agent中会有浏览器类型和版本信息

IE:  MSIE

谷歌:Chrome

火狐:Firefox


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

椰汁菠萝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值