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中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...
随机推荐
- caffe_ssd学习-用自己的数据做训练
几乎没用过linux操作系统,不懂shell编程,linux下shell+windows下UltraEdit勉勉强强生成了train.txt和val.txt期间各种错误辛酸不表,照着examples/ ...
- IDEA相关知识整理
一.离线下载插件[也可以通过代理的方式下载插件] http://plugins.jetbrains.com/ 下载离线插件 settings -> plugins -> install p ...
- windows环境下 curl 安装和使用
curl下载地址:https://curl.haxx.se/download.html,拉到页面最底下,选择红色选中的那个CAB的进行下载,如下图所示: 下载完成后,解压. 解决windows控制台c ...
- tomcat2章1
package ex02.pyrmont; import java.io.File; public class Constants { public static final String WEB_R ...
- [转载]对称加密DES和TripleDES
一. 对称加密 对称加密,是一种比较传统的加密方式,其加密运算.解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码(称为对称密码).因此,通信双方都必须 ...
- Ford VCM II Ford VCM2 Diagnostic Tool with Ford IDS v108 Installed On Laptop Ready to Use
HOW to VCM2 Ford VCM II with Ford IDS v108 Work Well? VCM2 Ford VCM2 Ford diagnostic tool hot sale i ...
- java加载配置文件信息
#基金数据存放根目录fund_save_root_path=E:/fundCrawling #龙虎榜数据存放根目录long_hu_root_path=E:/longHuCrawling #巨潮数据存放 ...
- oj练习---dp专题
1.POJ 3744 Scout YYF I 经典的dp模型,但是要用到快速矩阵幂加速,分段的思想 # include <stdio.h> # include <algorithm& ...
- cat <<-EOF >&2
cat <<-EOF >&2 cat >&2 <==> cat 1>&2 标准输出被重定向到错误输出 默认屏幕 <替换 < ...
- #mxnet# 权值共享
https://www.cnblogs.com/chenyliang/p/6847744.html Note:后记此权值共享非彼卷积共享.说的是layer实体间的参数共享. Introduction ...