//下载方法
public static void downLoad(HttpServletRequest request,HttpServletResponse resp, String allPath, String suffix, ZzFiles zzfile){
resp.setCharacterEncoding("utf-8");
//根据后缀判断resp的题头文件
if(".html".equals(suffix)){
resp.setContentType("text/html");
} else if(".doc".equals(suffix)){
resp.setContentType("application/msword");
} else if(".pdf".equals(suffix)){
resp.setContentType("application/PDF");
} else if(".dbf".equals(suffix)){
resp.setContentType("application/x-dbf");
}else{
resp.setContentType("application/octet-stream");
}
String name="";
if(zzfile!=null){
name=zzfile.getFilename();
String userAgent = request.getHeader("User-Agent");
try {
if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {
name=java.net.URLEncoder.encode(name,"UTF-8");
}else {
name=new String(name.getBytes("UTF-8"),"ISO-8859-1");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else{
//这里是一个生成名字的方法,我是用了一个我们自己的公共类,按照日期生成名字
name = new Date().getTime() + suffix;
}
resp.addHeader("Content-Disposition", "attachment;filename=\"" + name+"\"" );
//开始下载
File file = new File(allPath);
try {
InputStream fin = new FileInputStream(file);
ServletOutputStream out = resp.getOutputStream();
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
if(fin!=null){
fin.close();
}
if(out!=null){
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Java Web中下载文件时,如果文件名中有空格,用火狐下载时会被截断(如:Text 123.pdf),会显示为 Text,处理很简单,只要在设置文件名的地方加上“”就可以了。
resp.addHeader("Content-Disposition", "attachment;filename=\"" + name+"\"" );
这样仍有一些会乱码 换成下边方式后解决
name=zzfile.getFilename();
String userAgent = request.getHeader("User-Agent");
try {
if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {
name=java.net.URLEncoder.encode(name,"UTF-8");
}else {
//name=new String(name.getBytes("UTF-8"),"ISO-8859-1");
name="=?UTF-8?B?"+new String(Base64.getEncoder().encodeToString(name.getBytes("utf-8")))+"?=";
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}