首页 > 代码库 > servlet实现多文件打包下载

servlet实现多文件打包下载

当用户一次下载多个文件时,一般情况是,每下载一个文件,均要弹出一个下载的对话框,这给用户造成了很大不便。

比较理想的情况是,用户选择多个文件后,服务器后端直接将多个文件打包为zip。下面贴出实现代码。


前端Javascript代码(使用Javascript创建表单,通过提交表单的方式访问后端的MultiDownload):

var tmpForm = document.createElement("form");
tmpForm.id = "form1" ; 
tmpForm.name = "form1" ;                     
document.body.appendChild(tmpForm);
                                                
var tmpInput = document.createElement("input"); 
// 设置input相应参数 
tmpInput.type = "text"; 
tmpInput.name = "fileUrls" ; 
tmpInput.value = http://www.mamicode.com/downloadUrls;>
//从html从移除该form
document.body.removeChild(tmpForm);

后端MultiDownload代码:

public class MultiDownload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MultiDownload() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String strArray = null;
		strArray = request.getParameter("fileUrls");
		//传递到servlet时,默认将编码转换为ISO-8859-1,将其重新转码为GBK
		strArray=new String(strArray.getBytes("ISO-8859-1"), "GBK"); 
		String[] filePathArray = strArray.split(",");
		String zipFileName = "product.zip";
		response.setContentType("application/x-msdownload" ); // 通知客户文件的MIME类型:
		response.setHeader("Content-disposition" , "attachment;filename=" + zipFileName);
		//要下载的文件目录
		ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
		for (String filePath : filePathArray) {
			File file = new File(filePath);
			doZip(file, zos);
		}			
		zos.close();
	}
	/**
	 *  打包为 zip 文件
	 * @param file 待打包的文件
	 * @param zos zip zip输出流
	 * @throws IOException 
	 */
	private void doZip(File file, ZipOutputStream zos)
			throws IOException {
		if(file.exists()) {
			if (file.isFile()) {
				//如果是文件,写入到 zip 流中
				zos.putNextEntry(new ZipEntry(file.getName()));
				FileInputStream fis = new FileInputStream(file);
				byte[] buffer = new byte[1024];
				int r = 0;
				while ((r = fis.read(buffer)) != -1) {
					zos.write(buffer, 0, r);
				}
				zos.flush();				
				fis.close();
			} else {
				//如果是目录。递归查找里面的文件
				String dirName = file.getName() + "/";
				zos.putNextEntry(new ZipEntry(dirName));
				File[] subs = file.listFiles();
				for (File f : subs) {
					makeZip(f, dirName, zos);
				}
			}
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}


servlet实现多文件打包下载