首页>代码>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();
	}

}
最近下载更多
磊哥哥哥哥  LV13 2023年12月26日
a82338181  LV7 2021年9月2日
明123456  LV11 2021年5月27日
CC1999  LV14 2020年5月25日
li0426  LV3 2020年1月22日
liuyan1234  LV9 2019年5月27日
songlijun  LV13 2019年5月3日
pahirdin  LV12 2019年4月17日
f123654789  LV17 2018年12月16日
幸运疯子  LV13 2018年10月28日
最近浏览更多
磊哥哥哥哥  LV13 2023年12月26日
WBelong  LV7 2023年12月19日
uni-code_0123  LV1 2023年11月29日
jameshkj  LV8 2023年5月18日
ly4910  LV3 2023年2月21日
飘忽的茶树  LV9 2022年6月6日
bai620123  LV16 2022年4月16日
木易雨山  LV7 2021年11月2日
zql666  LV9 2021年9月28日
CoderMars  LV13 2021年9月10日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友