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>