zoukankan      html  css  js  c++  java
  • 【Java】Java批量文件打包下载zip

    网上看了很多,本文使用ant.jar中的org.apache.tools.zip,页面用js表单提交

    代码供参考:

    ACTION:

      1 /*
      2      * 另存为
      3      */
      4     @RequestMapping("/saveAs.do")
      5     public @ResponseBody
      6     void saveAs(String filePath, String fileName) {
      7 
      8         try {
      9             File file = new File(filePath);
     10             // 设置文件MIME类型
     11             getResponse().setContentType(getMIMEType(file));
     12             // 设置Content-Disposition
     13             getResponse().setHeader(
     14                     "Content-Disposition",
     15                     "attachment;filename="
     16                             + URLEncoder.encode(fileName, "UTF-8"));
     17             // 获取目标文件的绝对路径
     18             String fullFileName = getRealPath("/upload/" + filePath);
     19             // System.out.println(fullFileName);
     20             // 读取文件
     21             InputStream ins = new FileInputStream(fullFileName);
     22             // 放到缓冲流里面 
     23             BufferedInputStream bins = new BufferedInputStream(ins);
     24             // 获取文件输出IO流  
     25             // 读取目标文件,通过response将目标文件写到客户端
     26             OutputStream outs = getResponse().getOutputStream();
     27             BufferedOutputStream bouts = new BufferedOutputStream(outs);  
     28             // 写文件
     29              int bytesRead = 0;  
     30              byte[] buffer = new byte[8192];  
     31              // 开始向网络传输文件流  
     32              while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {  
     33                  bouts.write(buffer, 0, bytesRead);  
     34              }  
     35              bouts.flush();// 这里一定要调用flush()方法  
     36              ins.close();  
     37              bins.close();  
     38              outs.close();  
     39              bouts.close();  
     40         } catch (Exception e) {
     41             e.printStackTrace();
     42         }
     43     }
     44 
     45     /*
     46      * 批量下载另存为
     47      */
     48     @RequestMapping("/batDownload.do")
     49     public @ResponseBody
     50     void batDownload(String filePaths, String fileNames) {
     51         String tmpFileName = "work.zip";  
     52         byte[] buffer = new byte[1024];  
     53         String strZipPath = getRealPath("/upload/work/"+tmpFileName);
     54         try {
     55             ZipOutputStream out = new ZipOutputStream(new FileOutputStream(  
     56                         strZipPath));  
     57             String[] files=filePaths.split("\|",-1);
     58             String[] names=fileNames.split("\|",-1);
     59             // 下载的文件集合
     60             for (int i = 0; i < files.length; i++) {  
     61                 FileInputStream fis = new FileInputStream(getRealPath("/upload/"+files[i]));  
     62                 out.putNextEntry(new ZipEntry(names[i])); 
     63                  //设置压缩文件内的字符编码,不然会变成乱码  
     64                 out.setEncoding("GBK");  
     65                 int len;  
     66                 // 读入需要下载的文件的内容,打包到zip文件  
     67                 while ((len = fis.read(buffer)) > 0) {  
     68                     out.write(buffer, 0, len);  
     69                 }  
     70                 out.closeEntry();  
     71                 fis.close();  
     72             }
     73              out.close();  
     74              saveAs("work/"+tmpFileName, tmpFileName);  
     75 
     76         } catch (Exception e) {
     77             e.printStackTrace();
     78         }
     79     }
     80 
     81     /**
     82      * 根据文件后缀名获得对应的MIME类型。
     83      * 
     84      * @param file
     85      */
     86     private String getMIMEType(File file) {
     87         String type = "*/*";
     88         String fName = file.getName();
     89         // 获取后缀名前的分隔符"."在fName中的位置。
     90         int dotIndex = fName.lastIndexOf(".");
     91         if (dotIndex < 0) {
     92             return type;
     93         }
     94         /* 获取文件的后缀名 */
     95         String end = fName.substring(dotIndex, fName.length()).toLowerCase();
     96         if (end == "")
     97             return type;
     98         // 在MIME和文件类型的匹配表中找到对应的MIME类型。
     99         for (int i = 0; i < MIME_MapTable.length; i++) {
    100             if (end.equals(MIME_MapTable[i][0]))
    101                 type = MIME_MapTable[i][1];
    102         }
    103         return type;
    104     }
    105 
    106     private final String[][] MIME_MapTable = {
    107             // {后缀名, MIME类型}
    108             { ".doc", "application/msword" },
    109             { ".docx",
    110                     "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
    111             { ".xls", "application/vnd.ms-excel" },
    112             { ".xlsx",
    113                     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
    114             { ".pdf", "application/pdf" },
    115             { ".ppt", "application/vnd.ms-powerpoint" },
    116             { ".pptx",
    117                     "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
    118             { ".txt", "text/plain" }, { ".wps", "application/vnd.ms-works" },
    119             { "", "*/*" } };
    120 };

    <
    form id="batForm" action="<%=path%>/file/batDownload.do" method="post"> <input type="hidden" id="filePaths" name="filePaths" value=""/> <input type="hidden" id="fileNames" name="fileNames" value=""/> </form>
    function download(){
            var objs=$("#fileFrame").contents().find("input[name='ckFile']:checked");        
            if(objs.length>0){
                var filePaths="";
                var fileNames="";
                for(var i=0;i<objs.length;i++){                
                    filePaths+=$("#fileFrame").contents().find("#path_"+objs[i].value).val()+"|";
                    fileNames+=$("#fileFrame").contents().find("#a_"+objs[i].value).html()+"|";
                }
                filePaths=filePaths.substring(0,filePaths.length-1);
                fileNames=fileNames.substring(0,fileNames.length-1);
                $("#filePaths").val(filePaths);
                $("#fileNames").val(fileNames);
                $("#batForm").submit();
            }else{
                alert("请选择需要下载的文件!");
                return false;
            }
        }
    持之以恒
  • 相关阅读:
    linux系统命令学习系列-用户切换命令su,sudo
    linux系统命令学习系列-用户组管理
    linux系统命令学习-用户管理
    python web开发-flask中sqlalchemy的使用
    python web开发-flask连接sqlite数据库
    python实现bt种子 torrent转magnet
    prefProvider.kt
    douyin-bot-代码
    pyadb关于python操作adb的资料
    bottle源码
  • 原文地址:https://www.cnblogs.com/zwqh/p/6264425.html
Copyright © 2011-2022 走看看