博客
关于我
zip文件上传、解压
阅读量:177 次
发布时间:2019-02-28

本文共 8757 字,大约阅读时间需要 29 分钟。

import java.io.File;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.zip.ZipEntry;import java.util.zip.ZipException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.lingala.zip4j.core.ZipFile;import net.lingala.zip4j.model.UnzipParameters;import net.lingala.zip4j.model.ZipParameters;import net.lingala.zip4j.util.Zip4jConstants;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.dom4j.DocumentException;import org.springframework.web.bind.ServletRequestBindingException;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.multiaction.MultiActionController;import com.dps.service.KmlService;import com.dps.bean.MapAccessBean;import com.dps.common.GetRealPath;import com.dps.config.SysConfig;import com.dps.i18n.Catalog;
/**	 * 备份	 * 	 * @param request	 * @param response	 * @throws Exception	 */	//synchronized用来加锁	public synchronized void backUp(HttpServletRequest request, HttpServletResponse response)			throws Exception {		String data = "许可无效!";		if (!MapAccessBean.getIsValid()) {			response.setContentType("text/html;charset=UTF-8");			// location.reload();			// data="";			data = "";			System.out.println("key01" + data);			// response.sendRedirect("backUpAndRestore.htm");			response.getWriter().print(data);			return;		}				// 如果都没有选中		if(!("on".equals(request.getParameter("KMLModel")))&&!("on".equals(request.getParameter("lic")))){			data="请勾选需要还原的文件!";			response.setContentType("text/html;charset=UTF-8");			// location.reload();			// data="";			data = "";			// response.sendRedirect("backUpAndRestore.htm");			response.getWriter().print(data);			return;					}				// 在该位置判断,如果都没有进行勾选,则提示用户需要勾选备份		final String KMLModel = GetRealPath.getRootPath() + File.separatorChar + "KmlModel";		//final String KML = GetRealPath.getRootPath() + "\\KML";		final String images = GetRealPath.getRootPath() + File.separatorChar + "images";		final String layerTree = GetRealPath.getRootPath() + File.separatorChar + "tree.xml";		//final String sysconfig = GetRealPath.getRootPath()				//+ "\\sysconfig\\sysconfig.xml";		final String lic = GetRealPath.getRootPath() + File.separatorChar + "sysconfig" + File.separatorChar;		String filePath = tempPath + File.separatorChar + "backUp.zip";		File f = new File(tempPath);		if (!f.exists()){			f.mkdir();		}		f = new File(filePath);		if (f.exists()){			f.delete();		}		ZipFile zipFile = new ZipFile(filePath);			ZipParameters parameters = new ZipParameters();		// 设置压缩方法		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);		parameters.setEncryptFiles(true);        parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式          parameters.setPassword("!@#$%^&*()");  		// 设置压缩级别		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);		if ("on".equals(request.getParameter("KMLModel"))) {			f = new File(KMLModel);			if (!f.exists())				f.mkdir();			zipFile.addFolder(KMLModel, parameters);			zipFile.addFolder(images, parameters);			zipFile.addFile(new File(layerTree), parameters);		}//		if ("on".equals(request.getParameter("KML"))) {//			f = new File(KML);//			if (!f.exists())//				f.mkdir();//			zipFile.addFolder(KML, parameters);//		//		}//		if ("on".equals(request.getParameter("images")))//			zipFile.addFolder(images, parameters);//		if ("on".equals(request.getParameter("layerTree")))//			zipFile.addFile(new File(layerTree), parameters);//		if ("on".equals(request.getParameter("sysconfig")))//			zipFile.addFile(new File(sysconfig), parameters);		if ("on".equals(request.getParameter("lic"))) {			f = new File(lic);			String[] filelist = f.list();			if (f.list() != null) {				for (String fileName : filelist) {					if (fileName.lastIndexOf(".lic") != -1)						zipFile.addFile(new File(lic + fileName), parameters);				}			}		} 							 if (!zipFile.isValidZipFile()) {  	            throw new ZipException("压缩文件不合法,可能被损坏.");  	        }  		response.reset();		response.setContentType("application/zip");		response.setHeader("Content-Disposition",				"attachment; filename=backUp.zip");		java.io.FileInputStream in = new java.io.FileInputStream(filePath);		byte[] b = new byte[512];		ServletOutputStream o = null;		try {						o = response.getOutputStream();			int bytesRead;			while (-1 != (bytesRead = in.read(b, 0, b.length))) {				o.write(b, 0, bytesRead);			}			in.close();			o.close();			response.flushBuffer();					} catch (IOException e) {			in.close();			//o.close();			//response.flushBuffer();						System.out.println(e.getMessage());		} catch (Exception e) {						System.out.println(e.getMessage());		} finally {			// // o.close();			// if (o != null) {			// o.close();			// }			// if (in != null) {			// in.close();			// }		}		try {			File f2 = new File(filePath);			if (f2.exists()){				f2.delete();			}			//new File(filePath).delete();		} catch (Exception e) {			e.printStackTrace();		}	}	/**	 * 还原	 * 	 * @param request	 * @param response	 * @throws Exception	 */	public ModelAndView restore(HttpServletRequest request,			HttpServletResponse response)  {		ModelAndView modelAndView = new ModelAndView();		modelAndView.setViewName("backUpAndRestore");		File f = new File(tempPath);		System.out.println("tempPath:"+tempPath);		if (!f.exists())			f.mkdir();		String data = "许可无效!";		// 文件上传处理工厂		FileItemFactory factory = new DiskFileItemFactory();		// 创建文件上传处理器		ServletFileUpload upload = new ServletFileUpload(factory);		HashMap
params = new HashMap
(); // 开始解析请求信息 List items = null; try { items = upload.parseRequest(request); for (Iterator it = items.iterator(); it.hasNext();) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { try { params .put(fileItem.getFieldName(), fileItem .getString("UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { String fileName = fileItem.getName(); if (!fileName.endsWith(".zip")) { try { throw new Exception(Catalog .getLocalizationForKey("KmlController.ZIPAllowed")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 将文件写入 File file = new File(tempPath, "restore.zip"); try { fileItem.write(file); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // 解压 ZipFile zipFile; try { zipFile = new ZipFile(file); if (!zipFile.isValidZipFile()) { try { throw new ZipException("压缩文件不合法,可能被损坏."); } catch (ZipException e) { // TODO Auto-generated catch block e.printStackTrace(); data = "1";//压缩文件不合法,可能被损坏 modelAndView.addObject("message", data); return modelAndView; } } if(zipFile.isEncrypted()){ zipFile.setPassword("!@#$%^&*()"); zipFile.extractAll(GetRealPath.getRootPath()); }else{ //data = "备份数据文件无效,请选择正确的压缩文件!"; data = "2";//"备份数据文件无效,请选择正确的压缩文件!"; modelAndView.addObject("message", data); return modelAndView; } } catch (net.lingala.zip4j.exception.ZipException e1) { // TODO Auto-generated catch block e1.printStackTrace(); //data = "解压密码错误,请选择有效的文件!"; data = "3";//解压密码错误,请选择有效的文件! modelAndView.addObject("message", data); return modelAndView; } file.delete(); } } } catch (FileUploadException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (!MapAccessBean.getIsValid()) { // response.setContentType("text/html;charset=UTF-8"); // location.reload(); // data="
"; // data="
"; data="4"; modelAndView.addObject("message", data); return modelAndView; // response.sendRedirect("backUpAndRestore.htm"); // response.getWriter().print(data); // throw new // Exception(Catalog.getLocalizationForKey("KmlController.licError")); } else { modelAndView.addObject("message", Catalog .getLocalizationForKey("KmlController.restorSuccess")); if ("on".equals(params.get("checkURL"))) try { kmlService.checkIconUrl(request.getServerName() + ":" + request.getServerPort()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // 重新加载系统配置 SysConfig.getInstance().init(); } return modelAndView; }

转载地址:http://dwvj.baihongyu.com/

你可能感兴趣的文章
MySQL 是怎样运行的 - InnoDB数据页结构
查看>>
mysql 更新子表_mysql 在update中实现子查询的方式
查看>>
MySQL 有什么优点?
查看>>
mysql 权限整理记录
查看>>
mysql 权限登录问题:ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: YES)
查看>>
MYSQL 查看最大连接数和修改最大连接数
查看>>
MySQL 查看有哪些表
查看>>
mysql 查看锁_阿里/美团/字节面试官必问的Mysql锁机制,你真的明白吗
查看>>
MySql 查询以逗号分隔的字符串的方法(正则)
查看>>
MySQL 查询优化:提速查询效率的13大秘籍(避免使用SELECT 、分页查询的优化、合理使用连接、子查询的优化)(上)
查看>>
mysql 查询数据库所有表的字段信息
查看>>
【Java基础】什么是面向对象?
查看>>
mysql 查询,正数降序排序,负数升序排序
查看>>
MySQL 树形结构 根据指定节点 获取其下属的所有子节点(包含路径上的枝干节点和叶子节点)...
查看>>
mysql 死锁 Deadlock found when trying to get lock; try restarting transaction
查看>>
mysql 死锁(先delete 后insert)日志分析
查看>>
MySQL 死锁了,怎么办?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 添加列,修改列,删除列
查看>>