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;
}
springmvc上传zip文件并解压缩代码示例的更多相关文章
- SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html
SpringMVC上传压缩文件,解压文件,并检测上传文件中是否有index.html 说明: 1.环境:SpringMVC+Spring+Tomcat7+JDK1.7 2.支持 zip和rar格式的压 ...
- php上传zip文件在线解压文件在指定目录下,CI框架版本
我从网上找的文件php在线解压zip压缩文件 文件为jy.php可以直接执行,但是怎样将其加到CI框架中呢?? jy.php文件 <?php header("content-Type: ...
- .NetCore上传多文件的几种示例
本章和大家分享的是.NetCore的MVC框架上传文件的示例,主要讲的内容有:form方式提交上传,ajax上传,ajax提交+上传进度效果,Task并行处理+ajax提交+上传进度,相信当你读完文章 ...
- SpringMVC上传多文件
springMVC实现 多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实 现多文件上传效率上却有着很大的 ...
- js分片上传大文件,前端代码
首先导入jQuery.form.js文件,下面src是相对于改js文件位置, <script type="text/JavaScript" src="jquery/ ...
- C#上传数据到HTTP,HTTPS 代码示例
string param = string.Format("username={0}&password={1}", account, pwd); string result ...
- 【WCF】利用WCF实现上传下载文件服务
引言 前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...
- NetCore上传多文件
.NetCore上传多文件的几种示例 本章和大家分享的是.NetCore的MVC框架上传文件的示例,主要讲的内容有:form方式提交上传,ajax上传,ajax提交+上传进度效果,Task并行处理 ...
- SpringMVC+Ajax实现文件批量上传和下载功能实例代码
需求: 文件批量上传,支持断点续传. 文件批量下载,支持断点续传. 使用JS能够实现批量下载,能够提供接口从指定url中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...
随机推荐
- 【Hadoop学习之六】MapReduce原理
一.概念MapReduce:"相同"的key为一组,调用一次reduce方法,方法内迭代这一组数据进行计算 块.分片.map.reduce.分组.分区之间对应关系block > ...
- make: *** /lib/modules/3.10.0-327.el7.x86_64/build: 没有那个文件或目录。 停止。
1.问题: [root@localhost]# make make -C /lib/modules/-.el7.x86_64/build M=/home/csri/poc/adore modules ...
- [转载]PowerDesigner生成的ORACLE 建表脚本中去掉对象的双引号,设置大、小写
若要将 CDM 中将 Entity的标识符都设为指定的大小写,则可以这么设定: 打开cdm的情况下,进入Tools-Model Options-Naming Convention,把Name和Code ...
- java课上测试心得
放暑假之前,建民老师就给我们布置了每一天学习两小时的代码,但是自己的不重视,根本就没有达到这个要求,简单学了一点点基本的东西,然后在开学的第一堂课上,连续三个小时的敲代码,让我意识到了自己的问题,一个 ...
- Centos7升级gcc学习笔记 gcc 4.8.5 -> gcc 5.4.0
摘自:https://www.cnblogs.com/highway-9/p/5628852.html 一.安装开发必备环境: yum groupinstall "Development T ...
- Linux的简单介绍.
Linux操作系统概述: Linux是基于Unix的开源免费的操作系统,由于系统的稳定性和安全性几乎成为程序代码运行的最佳系统环境.Linux是由Linux Torvalds(林纳斯·托瓦兹)起初开发 ...
- Linux查看机器和硬盘的SN
查看硬件RAID中某块硬盘SN # sas 口: [root@ ~]$ smartctl -a /dev/sda -d megaraid,n *** Serial number: 6RJ974SR * ...
- RGB颜色对照表
RGB颜色对照表 https://www.cnblogs.com/android100/p/android-rgb-list.html #FFFFFF #FFFFF0 #FFFFE0 ...
- [WCF REST] 一个简单的REST服务实例
Get:http://www.cnblogs.com/artech/archive/2012/02/04/wcf-rest-sample.html [01] 一个简单的REST服务实例 [02] We ...
- 07:vue定义路由
1.1 定义路由 1.说明 1. 路由是单页面应用程序(SPA)的关键,Vue提供过来路由插件,使用这个路由就要安装这个插件 2. 安装: npm install vue-router 3. 依赖于v ...