SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html

时间:2021-05-11 14:31:17

SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html

说明:

1.环境:SpringMVC+Spring+Tomcat7+JDK1.7

2.支持 zip和rar格式的压缩文件上传和解压;

3.这里只提供处理上传文件的工具类,方法在Controller中进行的调用,前端View层进行文件上传的表单提交不再进行赘述。

---------------------------------------------------------------分割线------------------------------------------------------------------------------------------------

直接上代码

1.Controller中的调用

         /**
* 上传压缩文件
*/
@RequestMapping("/uploadPushContent.do")
@ResponseBody
public Object uploadPushContent(MultipartFile pushContent,HttpSession session,HttpServletRequest request){
Map<String,Object> jsonMap = new HashMap<String,Object>();
if(pushContent == null){
jsonMap.put(Constant.SUCCESS,false);
jsonMap.put(Constant.ERROR_MSG,"上传文件不能为空");
}else{
//获取存储文件的目录
//String path = session.getServletContext().getRealPath("/upload");
String path = Constant.UPLOAD_FILE_PATH;
try {
String saveFileName = UploadUtil.resolveCompressUploadFile(request, pushContent, path);
String url = Constant.URL_PRE_FILE+saveFileName+"/"+"index.html";
System.out.println("urlFile"+url);
jsonMap.put(Constant.SUCCESS,true);
jsonMap.put("url",url);
} catch (Exception e) {
jsonMap.put(Constant.SUCCESS,false);
jsonMap.put(Constant.ERROR_MSG,e.getMessage());
e.printStackTrace();
}
} return jsonMap;
}

上传压缩文件SpringMVC Controller的方法

2.接收&处理上传的压缩文件

 package com.xxxxxxx;

 import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile; import com.freesj.contentpush.common.constant.Constant; /**
* 上传文件工具类
*
* <p>ClassName:UploadUtil<p>
* <p>Description:<p>
*
* @author SuiAn
* @date 2017年8月22日下午4:53:55
*/
public class UploadUtil { /**
* 解析上传的压缩文件
* @param request 请求
* @param file 上传文件
* @return
* @throws Exception
*/
public static String resolveCompressUploadFile(HttpServletRequest request,MultipartFile file,String path) throws Exception { /* 截取后缀名 */
if (file.isEmpty()) {
throw new Exception("文件不能为空");
}
String fileName = file.getOriginalFilename();
int pos = fileName.lastIndexOf(".");
String extName = fileName.substring(pos+1).toLowerCase();
//判断上传文件必须是zip或者是rar否则不允许上传
if (!extName.equals("zip")&&!extName.equals("rar")) {
throw new Exception("上传文件格式错误,请重新上传");
}
// 时间加后缀名保存
String saveName = UUIDGenerator.getUUID()+ "."+extName;
//文件名
String saveFileName = saveName.substring(0, saveName.lastIndexOf("."));
// 根据服务器的文件保存地址和原文件名创建目录文件全路径
File pushFile = new File(path + "/" +saveFileName+"/"+ saveName); File descFile = new File(path+"/"+saveFileName);
if (!descFile.exists()) {
descFile.mkdirs();
}
//解压目的文件
String descDir = path +"/"+saveFileName+"/"; file.transferTo(pushFile); //开始解压zip
if (extName.equals("zip")) {
CompressFileUtils.unZipFiles(pushFile, descDir); }else if (extName.equals("rar")) {
//开始解压rar
CompressFileUtils.unRarFile(pushFile.getAbsolutePath(), descDir); } else {
throw new Exception("文件格式不正确不能解压");
}
//遍历文件夹
boolean isExist = checkIndexHtml(descDir);
if(!isExist){
throw new Exception("文件中缺少index.html");
}
return saveFileName;
} /**
* 检查是否有index.html
* @param strPath
* @return
*/
public static boolean checkIndexHtml(String strPath) {
boolean flag = false;
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if ("index.html".equals(fileName)) { // 判断是否有index.html
flag = true;
break;
}
}
}
return flag;
} }

处理上传压缩文件工具类

3.解压上传文件,检测上传文件中是否包含index.html

 package com.xxxxxx;

 import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile; import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader; public class CompressFileUtils {
/**
* 解压到指定目录
* @param zipPath
* @param descDir
* @author*/
public static void unZipFiles(String zipPath,String descDir)throws IOException{
unZipFiles(new File(zipPath), descDir);
}
/**
* 解压文件到指定目录
* @param zipFile
* @param descDir
* @author isea533
*/
@SuppressWarnings("rawtypes")
public static void unZipFiles(File zipFile,String descDir)throws IOException{
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = new ZipFile(zipFile);
for(Enumeration entries = zip.getEntries();entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replaceAll("\\*", "/");;
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//输出文件路径信息
System.out.println(outPath); OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
System.out.println("******************解压完毕********************");
} /**
* 根据原始rar路径,解压到指定文件夹下.
* @param srcRarPath 原始rar路径
* @param dstDirectoryPath 解压到的文件夹
*/
public static void unRarFile(String srcRarPath, String dstDirectoryPath) {
if (!srcRarPath.toLowerCase().endsWith(".rar")) {
System.out.println("非rar文件!");
return;
}
File dstDiretory = new File(dstDirectoryPath);
if (!dstDiretory.exists()) {// 目标目录不存在时,创建该文件夹
dstDiretory.mkdirs();
}
Archive a = null;
try {
a = new Archive(new File(srcRarPath));
if (a != null) {
a.getMainHeader().print(); // 打印文件信息.
FileHeader fh = a.nextFileHeader();
while (fh != null) {
if (fh.isDirectory()) { // 文件夹
File fol = new File(dstDirectoryPath + File.separator
+ fh.getFileNameString());
fol.mkdirs();
} else { // 文件
File out = new File(dstDirectoryPath + File.separator
+ fh.getFileNameString().trim());
//System.out.println(out.getAbsolutePath());
try {// 之所以这么写try,是因为万一这里面有了异常,不影响继续解压.
if (!out.exists()) {
if (!out.getParentFile().exists()) {// 相对路径可能多级,可能需要创建父目录.
out.getParentFile().mkdirs();
}
out.createNewFile();
}
FileOutputStream os = new FileOutputStream(out);
a.extractFile(fh, os);
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
fh = a.nextFileHeader();
}
a.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

解压上传的压缩文件,检测上传文件中是否包含index.html

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>