SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html
说明:
1.环境:SpringMVC+Spring+Tomcat7+JDK1.7
2.支持 zip和rar格式的压缩文件上传和解压;
3.这里只提供处理上传文件的工具类,方法在Controller中进行的调用,前端View层进行文件上传的表单提交不再进行赘述。
---------------------------------------------------------------分割线------------------------------------------------------------------------------------------------
直接上代码
1.Controller中的调用
1 /** 2 * 上传压缩文件 3 */ 4 @RequestMapping("/uploadPushContent.do") 5 @ResponseBody 6 public Object uploadPushContent(MultipartFile pushContent,HttpSession session,HttpServletRequest request){ 7 Map<String,Object> jsonMap = new HashMap<String,Object>(); 8 if(pushContent == null){ 9 jsonMap.put(Constant.SUCCESS,false); 10 jsonMap.put(Constant.ERROR_MSG,"上传文件不能为空"); 11 }else{ 12 //获取存储文件的目录 13 //String path = session.getServletContext().getRealPath("/upload"); 14 String path = Constant.UPLOAD_FILE_PATH; 15 try { 16 String saveFileName = UploadUtil.resolveCompressUploadFile(request, pushContent, path); 17 String url = Constant.URL_PRE_FILE+saveFileName+"/"+"index.html"; 18 System.out.println("urlFile"+url); 19 jsonMap.put(Constant.SUCCESS,true); 20 jsonMap.put("url",url); 21 } catch (Exception e) { 22 jsonMap.put(Constant.SUCCESS,false); 23 jsonMap.put(Constant.ERROR_MSG,e.getMessage()); 24 e.printStackTrace(); 25 } 26 } 27 28 return jsonMap; 29 }
2.接收&处理上传的压缩文件
1 package com.xxxxxxx; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.InputStream; 9 import java.io.OutputStream; 10 11 import javax.servlet.http.HttpServletRequest; 12 13 import org.apache.commons.fileupload.disk.DiskFileItem; 14 import org.springframework.web.multipart.MultipartFile; 15 import org.springframework.web.multipart.commons.CommonsMultipartFile; 16 17 import com.freesj.contentpush.common.constant.Constant; 18 19 /** 20 * 上传文件工具类 21 * 22 * <p>ClassName:UploadUtil<p> 23 * <p>Description:<p> 24 * 25 * @author SuiAn 26 * @date 2017年8月22日下午4:53:55 27 */ 28 public class UploadUtil { 29 30 /** 31 * 解析上传的压缩文件 32 * @param request 请求 33 * @param file 上传文件 34 * @return 35 * @throws Exception 36 */ 37 public static String resolveCompressUploadFile(HttpServletRequest request,MultipartFile file,String path) throws Exception { 38 39 /* 截取后缀名 */ 40 if (file.isEmpty()) { 41 throw new Exception("文件不能为空"); 42 } 43 String fileName = file.getOriginalFilename(); 44 int pos = fileName.lastIndexOf("."); 45 String extName = fileName.substring(pos+1).toLowerCase(); 46 //判断上传文件必须是zip或者是rar否则不允许上传 47 if (!extName.equals("zip")&&!extName.equals("rar")) { 48 throw new Exception("上传文件格式错误,请重新上传"); 49 } 50 // 时间加后缀名保存 51 String saveName = UUIDGenerator.getUUID()+ "."+extName; 52 //文件名 53 String saveFileName = saveName.substring(0, saveName.lastIndexOf(".")); 54 // 根据服务器的文件保存地址和原文件名创建目录文件全路径 55 File pushFile = new File(path + "/" +saveFileName+"/"+ saveName); 56 57 File descFile = new File(path+"/"+saveFileName); 58 if (!descFile.exists()) { 59 descFile.mkdirs(); 60 } 61 //解压目的文件 62 String descDir = path +"/"+saveFileName+"/"; 63 64 file.transferTo(pushFile); 65 66 //开始解压zip 67 if (extName.equals("zip")) { 68 CompressFileUtils.unZipFiles(pushFile, descDir); 69 70 }else if (extName.equals("rar")) { 71 //开始解压rar 72 CompressFileUtils.unRarFile(pushFile.getAbsolutePath(), descDir); 73 74 } else { 75 throw new Exception("文件格式不正确不能解压"); 76 } 77 //遍历文件夹 78 boolean isExist = checkIndexHtml(descDir); 79 if(!isExist){ 80 throw new Exception("文件中缺少index.html"); 81 } 82 return saveFileName; 83 } 84 85 /** 86 * 检查是否有index.html 87 * @param strPath 88 * @return 89 */ 90 public static boolean checkIndexHtml(String strPath) { 91 boolean flag = false; 92 File dir = new File(strPath); 93 File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组 94 if (files != null) { 95 for (int i = 0; i < files.length; i++) { 96 String fileName = files[i].getName(); 97 if ("index.html".equals(fileName)) { // 判断是否有index.html 98 flag = true; 99 break; 100 } 101 } 102 } 103 return flag; 104 } 105 106 }
3.解压上传文件,检测上传文件中是否包含index.html
1 package com.xxxxxx; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.util.Enumeration; 9 import org.apache.tools.zip.ZipEntry; 10 import org.apache.tools.zip.ZipFile; 11 12 import com.github.junrar.Archive; 13 import com.github.junrar.rarfile.FileHeader; 14 15 public class CompressFileUtils { 16 /** 17 * 解压到指定目录 18 * @param zipPath 19 * @param descDir 20 * @author*/ 21 public static void unZipFiles(String zipPath,String descDir)throws IOException{ 22 unZipFiles(new File(zipPath), descDir); 23 } 24 /** 25 * 解压文件到指定目录 26 * @param zipFile 27 * @param descDir 28 * @author isea533 29 */ 30 @SuppressWarnings("rawtypes") 31 public static void unZipFiles(File zipFile,String descDir)throws IOException{ 32 File pathFile = new File(descDir); 33 if(!pathFile.exists()){ 34 pathFile.mkdirs(); 35 } 36 ZipFile zip = new ZipFile(zipFile); 37 for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){ 38 ZipEntry entry = (ZipEntry)entries.nextElement(); 39 String zipEntryName = entry.getName(); 40 InputStream in = zip.getInputStream(entry); 41 String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");; 42 //判断路径是否存在,不存在则创建文件路径 43 File file = new File(outPath.substring(0, outPath.lastIndexOf('/'))); 44 if(!file.exists()){ 45 file.mkdirs(); 46 } 47 //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压 48 if(new File(outPath).isDirectory()){ 49 continue; 50 } 51 //输出文件路径信息 52 System.out.println(outPath); 53 54 OutputStream out = new FileOutputStream(outPath); 55 byte[] buf1 = new byte[1024]; 56 int len; 57 while((len=in.read(buf1))>0){ 58 out.write(buf1,0,len); 59 } 60 in.close(); 61 out.close(); 62 } 63 System.out.println("******************解压完毕********************"); 64 } 65 66 /** 67 * 根据原始rar路径,解压到指定文件夹下. 68 * @param srcRarPath 原始rar路径 69 * @param dstDirectoryPath 解压到的文件夹 70 */ 71 public static void unRarFile(String srcRarPath, String dstDirectoryPath) { 72 if (!srcRarPath.toLowerCase().endsWith(".rar")) { 73 System.out.println("非rar文件!"); 74 return; 75 } 76 File dstDiretory = new File(dstDirectoryPath); 77 if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹 78 dstDiretory.mkdirs(); 79 } 80 Archive a = null; 81 try { 82 a = new Archive(new File(srcRarPath)); 83 if (a != null) { 84 a.getMainHeader().print(); // 打印文件信息. 85 FileHeader fh = a.nextFileHeader(); 86 while (fh != null) { 87 if (fh.isDirectory()) { // 文件夹 88 File fol = new File(dstDirectoryPath + File.separator 89 + fh.getFileNameString()); 90 fol.mkdirs(); 91 } else { // 文件 92 File out = new File(dstDirectoryPath + File.separator 93 + fh.getFileNameString().trim()); 94 //System.out.println(out.getAbsolutePath()); 95 try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压. 96 if (!out.exists()) { 97 if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录. 98 out.getParentFile().mkdirs(); 99 } 100 out.createNewFile(); 101 } 102 FileOutputStream os = new FileOutputStream(out); 103 a.extractFile(fh, os); 104 os.close(); 105 } catch (Exception ex) { 106 ex.printStackTrace(); 107 } 108 } 109 fh = a.nextFileHeader(); 110 } 111 a.close(); 112 } 113 } catch (Exception e) { 114 e.printStackTrace(); 115 } 116 } 117 }
4.依赖
<!-- 导入zip解压包 -->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
<!-- 导入rar解压包 -->
<dependency>
<groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId>
<version>0.7</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>