springmvc上传zip文件并解压缩代码示例

<input type="file"  id="file"  name="file"> 

spring中的配置:

<!-- 上传附件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<!-- 上传最大限制 20M-->
<property name="maxUploadSize" value="20971520" />
<property name="maxInMemorySize" value="40960" />
<!-- resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>

用了ant里的zipfile对象因为可以设置编码问题解决中文乱码:

<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>

 

@RequestMapping(value = "/add")
public String add(@RequestParam("file") CommonsMultipartFile file, MktSpecial mktSpecial,HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
// 清除上次上传进度信息
String curProjectPath = session.getServletContext().getRealPath("/");
String saveDirectoryPath = curProjectPath + uploadFolderName;
log.info("上传保存目录:"+saveDirectoryPath);
String unzipPath = curProjectPath + mktSpecial.getHtmlEn();
log.info("上传解压主题目录:"+unzipPath);
File saveDirectory = new File(saveDirectoryPath);
if(!saveDirectory.isDirectory()){
saveDirectory.mkdir();
}
File unzipPathDirectory = new File(unzipPath);
if(!unzipPathDirectory.isDirectory()){
unzipPathDirectory.mkdir();
}
log.info("Project real path [" + saveDirectory.getAbsolutePath() + "]");
// 判断文件是否存在
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
mktSpecial.setZipName(fileName);
String fileExtension = FilenameUtils.getExtension(fileName);
if (!ArrayUtils.contains(extensionPermit, fileExtension)) {
log.info("专题列表的压缩文件扩展名不对");
throw new Exception("No Support extension.");
}
// 通过CommonsMultipartFile的方法直接写文件(注意这个时候)
File newUploadFile=new File(saveDirectory, fileName);
file.transferTo(newUploadFile);
//解压缩
zipToFile( saveDirectoryPath+File.separator +fileName, unzipPath) ;
//删除原上传文件
newUploadFile.delete();

}

mktSpecial.setCreateTime(new Date());
mktSpecial.setIsUsable(Constants.UsableStatus.YES);
int addCount=mktSpecialService.insertSelective(mktSpecial);
if(addCount>0){
setUserManageOperateLog( request,Constants.UserManageOperateMode.other,Constants.UserManageOperateType.add, "增加专题成功",JSONObject.toJSONString(mktSpecial));
}else{
setUserManageOperateLog( request,Constants.UserManageOperateMode.other,Constants.UserManageOperateType.add, "增加专题失败",JSONObject.toJSONString(mktSpecial));
}
return redirectTo( "/mktSpecial/list");
}

 

/**
* 解压zip文件
* @param sourceFile,待解压的zip文件; toFolder,解压后的存放路径
* @throws Exception
**/

public static void zipToFile(String sourceFile, String toFolder) throws Exception {
String toDisk = toFolder;//接收解压后的存放路径
ZipFile zfile = new ZipFile(sourceFile,"utf-8");//连接待解压文件
Enumeration zList = zfile.getEntries();//得到zip包里的所有元素
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
log.info("打开zip文件里的文件夹:"+ ze.getName() +"skipped...");
continue;
}
OutputStream outputStream=null;
InputStream inputStream =null;
try {
//以ZipEntry为参数得到一个InputStream,并写到OutputStream中
outputStream = new BufferedOutputStream(
new FileOutputStream(getRealFileName(toDisk, ze.getName())));
inputStream = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, readLen);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
log.info("解压失败:"+e.toString());
throw new IOException("解压失败:" + e.toString());
}finally{
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException ex) {

}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
inputStream=null;
outputStream=null;
}

}
zfile.close();
}
/**

* 给定根目录,返回一个相对路径所对应的实际文件名.

* @param zippath 指定根目录

* @param absFileName 相对路径名,来自于ZipEntry中的name

* @return java.io.File 实际的文件

*/

private static File getRealFileName(String zippath, String absFileName){
log.info("文件名:"+absFileName);
String[] dirs = absFileName.split("/" , absFileName.length());
File ret = new File(zippath);// 创建文件对象
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {// 检测文件是否存在
ret.mkdirs();// 创建此抽象路径名指定的目录
}
ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child 路径名字符串创建一个新 File 实例
return ret;
}

posted @ 2017-04-06 18:36  那家那人那小伙  阅读(8785)  评论(0编辑  收藏  举报