springMVC 上传压缩包文件、解压

参考目录:

              http://www.cnblogs.com/lvgg/p/6674916.html  (解压部分)

              https://zhidao.baidu.com/question/921668573902673459.html (上传文件部分)
没有直接用以上的代码,因为直接引用会有一些错误。

eclipse   tomcat  

jar包:

           1、如果是maven项目,

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

           2、如果不是,导入jar包  commons-io-1.4.jar  ,commons-lang-2.4.jar


spring配置文件application.xml:

         1、 <!-- 上传附件 -->
              <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>

             

         2、  为了让application.xml起作用,需要在web.xml中配置:

                              web.xml中:

                             <web-app>

                             <context-param>
                             <param-name>contextConfigLocation</param-name>
                             <param-value>classpath:applicationContext.xml</param-value>
                             </context-param>

                              </web-app>

jsp:
<form action="upload.do" method="post" enctype="multipart/form-data">  
<input type="file" name="file" /> <input type="submit" value="Submit" /></form> 

controller:

@Controller
public class FileUploadSu {
    /** ��־����*/
    private Log logger = LogFactory.getLog(this.getClass());

    private static final long serialVersionUID = 1L;

    /** �ϴ�Ŀ¼��*/
    private static final String uploadFolderName = "uploadFiles";

    /** �����ϴ�����չ��*/
    private static final String [] extensionPermit = {"txt", "xls", "zip"};

    @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> fileUpload(@RequestParam (value = "file", required = false)CommonsMultipartFile file,
                                   HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
        logger.info("UploadController#fileUpload() start");

       // 清除上次上传进度信息
        String curProjectPath = session.getServletContext().getRealPath("/");
        String saveDirectoryPath = curProjectPath + "/" + uploadFolderName;

        String saveZipPath=saveDirectoryPath+"/zips";
        File saveDirectory = new File(saveZipPath);
        logger.debug("Project real path [" + saveDirectory.getAbsolutePath() + "]");

        // 判断文件是否存在
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String fileExtension = FilenameUtils.getExtension(fileName);
            if(!ArrayUtils.contains(extensionPermit, fileExtension)) {
                //throw new NoSupportExtensionException("No Support extension.");
            }

         //下面的方法用于上传文件

            file.transferTo(new File(saveDirectory, fileName));
            String a[] = fileName.split("\\.");
            String saveUnZipPath=a[0];

            //解压缩,上传的压缩包存放在zips目录下,解压后的文件存在projects目录下

            FileUnZip.zipToFile(saveDirectoryPath+"/zips/"+fileName,saveDirectoryPath+"/projects/"+saveUnZipPath);
        }

        logger.info("UploadController#fileUpload() end");
       // return State.OK.toMap();
       
        Object obj;
        Map map=new HashMap();
        return map;
    }
}

解压的工具类:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

public class FileUnZip {
    /**
     * 解压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;
    }
}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值