代码段:
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