今天公司网盘的项目需求是要求可以选中多问件进行下载,所以接到需求就开始在网上找资料,一下就是捣鼓了一会儿的,
Servlet多文件打包下载代码如下:
项目下载地址:ServletDownload
所需要的jar包:
Servlet代码
package project;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.zip.*;
/**
* Servlet实现多文件打包下载
* @author Frank
*
*/
public class Download extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -1379339763454618902L;
public Download() {
super();
}
/**
* doPost提交方式
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/**
* doGet提交方式
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename="+ this.getZipFilename());
System.out.println("in BatchDownload................");
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
File[] files = new File[3];
/*这里可以根据前台进行赋值,我这样做事为了快速做测试而已 */
files[0] = new File("F:/1111.png");
files[1] = new File("F:/11.png");
files[2] = new File("D:/testduo");
for(File f:files){
zipFile(f, "", zos);
}
zos.flush();
zos.close();
}
/**
* 使用递归进行文件夹,文件的扫描
*/
private void zipFile(File subs, String baseName, ZipOutputStream zos)throws IOException {
if(subs.exists()){
if(subs.isFile()){
zos.putNextEntry(new ZipEntry(baseName + subs.getName()));
FileInputStream fis = new FileInputStream(subs);
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}else{
//如果是目录。递归查找里面的文件
String dirName = baseName + subs.getName() + "/";
zos.putNextEntry(new ZipEntry(dirName));
File[] sub = subs.listFiles();
for (File f : sub) {
zipFile(f, dirName, zos);
}
}
}
}
/**
* 获取zip文件名
* @return
*/
private String getZipFilename() {
Date date = new Date();
String s = date.getTime() + ".zip";
return s;
}
}
Web.xml配置
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>Down</servlet-name>
<servlet-class>project.Download</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Down</servlet-name>
<url-pattern>/scripts/Down</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
测试地址
在浏览器输入:http://localhost:8080/你的项目名称/scripts/Down
输入地址后就可以看到结果:
打开压缩包就可以看到下载的文件夹及文件: