zip文件上传、解压

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="<script>"+"alert('"+data+"');window.top.location='"+request.getContextPath()+"/backUpAndRestore.htm';"+"</script>";
			data = "<script>" + "alert('" + data + "');history.back();"
					+ "</script>";
			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="<script>"+"alert('"+data+"');window.top.location='"+request.getContextPath()+"/backUpAndRestore.htm';"+"</script>";
			data = "<script>" + "alert('" + data + "');history.back();"
					+ "</script>";
			// 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<String, String> params = new HashMap<String, String>();
		// 开始解析请求信息
		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="<script>"+"alert('"+data+"');window.top.location='"+request.getContextPath()+"/backUpAndRestore.htm';"+"</script>";


			// data="<script>"+"alert('"+data+"');history.back();"+"</script>";
            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;
	}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java实现zip文件上传解压的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/upload") @MultipartConfig // 必须加上此注解才能处理文件上传 public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上传的文件 Part filePart = request.getPart("file"); // 获取文件名 String fileName = filePart.getSubmittedFileName(); // 获取文件输入流 FileInputStream fileInputStream = (FileInputStream) filePart.getInputStream(); // 创建目标文件 File targetFile = new File(fileName); FileOutputStream fileOutputStream = new FileOutputStream(targetFile); // 将上传的文件写入到目标文件中 byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, len); } fileInputStream.close(); fileOutputStream.close(); // 解压文件 unzip(targetFile); // 输出成功信息 response.getWriter().println("文件上传解压成功!"); } private void unzip(File zipFile) throws IOException { // 创建解压目录 String unzipDir = zipFile.getName().substring(0, zipFile.getName().lastIndexOf('.')); File unzipDirFile = new File(unzipDir); unzipDirFile.mkdirs(); // 创建ZipInputStream ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); // 循环读取ZipEntry ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String entryName = zipEntry.getName(); String entryPath = unzipDir + File.separator + entryName; if (zipEntry.isDirectory()) { // 如果是目录,则创建目录 new File(entryPath).mkdirs(); } else { // 如果是文件,则写入文件 FileOutputStream fileOutputStream = new FileOutputStream(entryPath); byte[] buffer = new byte[1024]; int len; while ((len = zipInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.close(); } zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); } } ``` 该代码使用了Servlet 3.0规范的`@MultipartConfig`注解来处理文件上传,通过`request.getPart("file")`方法获取上传的文件。然后将文件写入到目标文件中,并调用`unzip()`方法解压文件。`unzip()`方法使用`ZipInputStream`读取zip文件中的每个`ZipEntry`,如果是目录则创建目录,如果是文件则写入文件。解压完成后,输出成功信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值