以下示例servlet显示了如何创建一个zip文件并发送生成的zip文件供用户下载。压缩过程zipFiles由此类的方法完成。
要使aservlet正常工作,您需要在web.xmlWeb应用程序的文件中对其进行配置,该文件可以在下面的代码段之后找到。
package org.nhooo.example.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipDownloadServlet extends HttpServlet {
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 下面的路径是要存储的数据的根目录
// 压缩。
String path = getServletContext().getRealPath("data");
File directory = new File(path);
String[] files = directory.list();
// 检查目录是否包含一些文件。
if (files != null && files.length > 0) {
// 调用zipFiles方法来创建一个zip流。
byte[] zip = zipFiles(directory, files);
//将响应发送回用户/浏览器。
//zip文件类型的内容为“ application/zip”。
// 还将内容处置设置为附件
// 在浏览器中显示一个对话框,该对话框将允许用户
// 选择他将对发送的内容采取什么措施。
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP"");
sos.write(zip);
sos.flush();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Compress the given directory with all its files.
*/
private byte[] zipFiles(File directory, String[] files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : files) {
FileInputStream fis = new FileInputStream(directory.getPath() +
ZipDownloadServlet.FILE_SEPARATOR + fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(fileName));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
bis.close();
fis.close();
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
}该web.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>ZipDownloadServlet</servlet-name> <servlet-class>org.nhooo.example.servlet.ZipDownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ZipDownloadServlet</servlet-name> <url-pattern>/zipservlet</url-pattern> </servlet-mapping> </web-app>