业务调用
if ("zip".equals(extension)) {
//压缩文件,返回新图片名称
List<Map<String, String>> mapList = FileUnZip.unZip(photoPath, realPath, false);
for (Map<String, String> map : mapList) {
String newFilename = map.get("newFilename").toString();
CasePhotos photos = new CasePhotos();
photos.setId(KeyUtils.get32UUID());
photos.setCaId(ca1.getId());
photos.setPhotoId(newFilename);
photos.setType("1");
casePhotosService.insertSelective(photos);
}
}
FileUnZip工具类
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
public class FileUnZip {
static final int BUFFER = 2048;
/**
* zip文件解压
* zip文件中多层目录不做处理,全部解压到传入的filePath下
* @param unZipfileName
* 要解压缩的文件全路径
* @param filePath
* 文件解压缩到的位置
* @return 压缩文件中的文件名和存储文件名
* @throws Exception
*/
public static List<Map<String, String>> unZip(String unZipfileName,
String filePath,boolean isYanZheng) throws Exception {
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
try {
ZipFile zipFile = new ZipFile(unZipfileName, "GB2312");
Enumeration<?> emu = zipFile.getEntries();
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
// 目录作为一个file读出,判断是目录则跳过。
if (entry.isDirectory()) {
continue;
}
String filePostfix = entry.getName().substring(
entry.getName().lastIndexOf(".")).toLowerCase();
// //判断文件
// if(fileType != null && !fileType.contains(filePostfix))
// continue;
String fileName = entry.getName().substring(entry.getName().lastIndexOf("/")+1);
String oldFilename = entry.getName().substring(entry.getName().lastIndexOf("/")+1,
entry.getName().lastIndexOf("."));
String newFilename = "";
if(isYanZheng){
newFilename = oldFilename;//验证时文件名不重新生成
}else{
newFilename = KeyUtils.get32UUID();//导入是文件名重新生成
}
String newFilePath = filePath + "\\" + newFilename + filePostfix;//解压到临时文件夹中,文件名不变
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
bis = new BufferedInputStream(zipFile.getInputStream(entry));
File file = new File(newFilePath);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
} finally {
bos.flush();
bos.close();
bis.close();
fos.close();
}
Map<String, String> map = new HashMap<String, String>();
map.put("newFilePath", newFilePath);//解压后文件路径
map.put("fileName", fileName);//解压前文件名有后缀
map.put("newFilename", newFilename);//解压后无后缀
System.out.println("newFilename="+newFilename);
result.add(map);
}
zipFile.close();
} catch (Exception e) {
throw e;
}
return result;
}
}