首页>代码>java servlet通过SmartUpload开发文件批量上传、批量下载源码分享>/fileBatchWithSmart/src/org/shengke/servlet/BatchDownloadServlet.java
package org.shengke.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 文件批量下载 */ public class BatchDownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req,resp); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub //设置文件头,类型为下载类型 resp.setContentType("application/x-msdownload"); //下载时浏览器提示用户保存的文件名filename=test.zip resp.setHeader("Content-Disposition", "attachment;filename=test.zip"); // String path = getServletContext().getRealPath("/") + "images/"; //设置下载文件的路径,文件在服务器上的位置 String path = "/home/shengke/workspace/wenjianSCXZ/WebContent/images/"; //初始化一个String数组,来存放下载文件名序列 String[] filenames = req.getParameterValues("filename"); String str = ""; //为了偷懒 String rt = "\r\n"; // 文件压缩,这是批量文件下载的关键,如果不对多个下载文件进行统一打包的话,下载时浏览器会弹出多个提示下载框,个用户体验不好 //使用zip方式压缩文件序列 ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream()); for(String filename : filenames){ str += filename + rt; File file = new File(path + filename); zos.putNextEntry(new ZipEntry(filename)); FileInputStream fis = new FileInputStream(file); //读取文件 byte b[] = new byte[1024]; int n = 0; while((n = fis.read(b)) != -1){ zos.write(b, 0, n); } zos.flush(); fis.close(); } zos.setComment("download success:" + rt + str); zos.flush(); zos.close(); } }