jar包复制到WEB-INF 文件夹lib下:
commons-io-1.3.2.jar
public static String download(HttpServletRequest request,
HttpServletResponse response, String urlandfile,String fileName) throws Exception {
String msg=null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
javax.servlet.ServletOutputStream ou = response.getOutputStream();
//文件名
// String filename=new String(fileName.getBytes("ISO8859_1"),"GB2312").toString();//解决中文乱码,此处不作处理
//路径
java.io.File file = new java.io.File(urlandfile);
if (!file.exists()) {
System.out.println(file.getAbsolutePath() + " 文件不能存在!");
msg="unexists";
return msg;
}
// 读取文件流
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(file);
// 下载文件
// 设置响应头和下载保存的文件名
response.setContentType("application/x-msdownload");//弹出下载的框
response.setContentLength((int) file.length());//下载统计文件大小的进度
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
//下载框的信息
if (fileInputStream != null) {
int filelen = fileInputStream.available();
//文件太大时内存不能一次读出,要循环
byte a[] = new byte[filelen];
fileInputStream.read(a);
ou.write(a);
}
fileInputStream.close();
ou.close();
msg="success";
} catch (Exception e) {
e.printStackTrace();
msg="error";
}
//解决完成后使用一切正常,但是总抛出java.lang.IllegalStateException异常主要是流还存在
return msg;
}
}
//解决完成后使用一切正常,但是总抛出java.lang.IllegalStateException异常主要是流还存在方法:
在返回界面(jsp)加上
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>操作成功</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%--下载成功之后需要清空流--%>
操作成功!
<%
out.clear();
out = pageContext.pushBody();
%>
</body>
</html>