- 首先,怎么做这个界面
你肯定需要从Tomcat服务器上获取这这些文件名。
<% //获取指定下载路径
String path = application.getRealPath("img");
File file = new File(path);
//得到此路径下所有文件的名字
String[] names = file.list();%>
<body>
<form action="dodownload.jsp" method="post">
//循环显示这些文件名
<%for(String name:names){ %>
<input type="checkbox" name="fileName" value="<%=name%>"/><%=name%><br>
<% }%>
<input type="submit" value="下载"/>
</form>
</body>
- 后台处理
<%
request.setCharacterEncoding("UTF-8");
//获取前端选中的文件名
String[] fileNames = request.getParameterValues("fileName");
//文件所在路径(File.separator可以根据操作系统需求而变,在windows上相当于‘\’)
String path = application.getRealPath("img")+File.separator;
//
OutputStream os = response.getOutputStream();
//指定zos输出到哪,在这里我们用response.getOutputStream()就可以在页面弹出的对话框进行选择
ZipOutputStream zout = new ZipOutputStream(os);
for(String fileName : fileNames){
//依次读取文件
FileInputStream fis = new FileInputStream(path+fileName);
// new ZipEntry(fileName): 使用指定名称创建新的 ZIP 条目
zout.putNextEntry(new ZipEntry(fileName));
byte[] b = new byte[1024];
int len;
while((len = fis.read(b))>0){
zout.write(b, 0, len);//写到压缩流
}
fis.close();
}
zout.close();
os.close();
%>
用IE测试是没问题的,因为这种写法太low,还有好多问题没有考虑到,望指正。