【Java】Java批量文件打包下載zip

網上看了不少,本文使用ant.jar中的org.apache.tools.zip,頁面用js表單提交html

代碼供參考:apache

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;
        }
    }
相關文章
相關標籤/搜索