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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM