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

代码供参考:

ACTION:

/*
     * 另存为
     */
    @RequestMapping("/saveAs.do")
    public @ResponseBody
    void saveAs(String filePath, String fileName) {
        try {
            File file = new File(filePath);
            // 设置文件MIME类型
            getResponse().setContentType(getMIMEType(file));
            // 设置Content-Disposition
            getResponse().setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + URLEncoder.encode(fileName, "UTF-8"));
            // 获取目标文件的绝对路径
            String fullFileName = getRealPath("/upload/" + filePath);
            // System.out.println(fullFileName);
            // 读取文件
            InputStream ins = new FileInputStream(fullFileName);
            // 放到缓冲流里面 
            BufferedInputStream bins = new BufferedInputStream(ins);
            // 获取文件输出IO流  
            // 读取目标文件,通过response将目标文件写到客户端
            OutputStream outs = getResponse().getOutputStream();
            BufferedOutputStream bouts = new BufferedOutputStream(outs);  
            // 写文件
             int bytesRead = 0;  
             byte[] buffer = new byte[8192];  
             // 开始向网络传输文件流  
             while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {  
                 bouts.write(buffer, 0, bytesRead);  
             }  
             bouts.flush();// 这里一定要调用flush()方法  
             ins.close();  
             bins.close();  
             outs.close();  
             bouts.close();  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * 批量下载另存为
     */
    @RequestMapping("/batDownload.do")
    public @ResponseBody
    void batDownload(String filePaths, String fileNames) {
        String tmpFileName = "work.zip";  
        byte[] buffer = new byte[1024];  
        String strZipPath = getRealPath("/upload/work/"+tmpFileName);
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(  
                        strZipPath));  
            String[] files=filePaths.split("\\|",-1);
            String[] names=fileNames.split("\\|",-1);
            // 下载的文件集合
            for (int i = 0; i < files.length; i++) {  
                FileInputStream fis = new FileInputStream(getRealPath("/upload/"+files[i]));  
                out.putNextEntry(new ZipEntry(names[i])); 
                 //设置压缩文件内的字符编码,不然会变成乱码  
                out.setEncoding("GBK");  
                int len;  
                // 读入需要下载的文件的内容,打包到zip文件  
                while ((len = fis.read(buffer)) > 0) {  
                    out.write(buffer, 0, len);  
                }  
                out.closeEntry();  
                fis.close();  
            }
             out.close();  
             saveAs("work/"+tmpFileName, tmpFileName);  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据文件后缀名获得对应的MIME类型。
     * 
     * @param file
     */
    private String getMIMEType(File file) {
        String type = "*/*";
        String fName = file.getName();
        // 获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "")
            return type;
        // 在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }
    private final String[][] MIME_MapTable = {
            // {后缀名, MIME类型}
            { ".doc", "application/msword" },
            { ".docx",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
            { ".xls", "application/vnd.ms-excel" },
            { ".xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
            { ".pdf", "application/pdf" },
            { ".ppt", "application/vnd.ms-powerpoint" },
            { ".pptx",
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
            { ".txt", "text/plain" }, { ".wps", "application/vnd.ms-works" },
            { "", "*/*" } };
};
<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;
        }
    }

DEMO下载地址:https://dwz.cn/Jw3z6fVq

【Java】Java批量文件打包下载zip的更多相关文章

  1. Java批量文件打包下载zip

    网上看了很多,本文使用ant.jar中的org.apache.tools.zip,页面用js表单提交 代码供参考: ACTION: /* * 另存为 */ @RequestMapping(" ...

  2. PHP 多文件打包下载 zip

    <?php $zipname = './photo.zip'; //服务器根目录下有文件夹public,其中包含三个文件img1.jpg, img2.jpg, img3.jpg,将这三个文件打包 ...

  3. Java批量文件打包下载

    经常遇到选择多个文件进行批量下载的情况,可以先将选择的所有的文件生成一个zip文件,然后再下载,该zip文件,即可实现批量下载,但是在打包过程中,常常也会出现下载过来的zip文件中里面有乱码的文件名, ...

  4. java 实现多文件打包下载

    jsp页面js代码: function downloadAttached(){ var id = []; id.push(infoid); var options = {}; options.acti ...

  5. 使用PHP自带zlib函数 几行代码实现PHP文件打包下载zip

    <?php //获取文件列表 function list_dir($dir){ $result = array(); if (is_dir($dir)){ $file_dir = scandir ...

  6. 几行代码轻松实现PHP文件打包下载zip

    <?php //获取文件列表 function list_dir($dir){ $result = array(); if (is_dir($dir)){ $file_dir = scandir ...

  7. PHP扩展类ZipArchive实现压缩解压Zip文件和文件打包下载 && Linux下的ZipArchive配置开启压缩 &&搞个鸡巴毛,写少了个‘/’号,浪费了一天

    PHP ZipArchive 是PHP自带的扩展类,可以轻松实现ZIP文件的压缩和解压,使用前首先要确保PHP ZIP 扩展已经开启,具体开启方法就不说了,不同的平台开启PHP扩增的方法网上都有,如有 ...

  8. java将文件打包成ZIP压缩文件的工具类实例

    package com.lanp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  9. java 多个文件打包zip

    /** * 多个文件打包成zip */ public class ZipDemo { private static void create() throws Exception{ String pat ...

随机推荐

  1. 在微信小程序中调用本地接口

    1.点击详情,并勾选项目设置中最后一行. 2.用小程序请求本地的后台服务接口 wx.request({ url: 'http://localhost:8090/DemoProject/myTest.d ...

  2. Composer 安装以及使用方法

    Composer 是 PHP 的一个依赖管理工具.它允许你申明项目所依赖的代码库,它会在你的项目中为你安装他们. Linux 下安装 curl -sS https://getcomposer.org/ ...

  3. jquery ajax 中实现给变量赋值

    我们在用JQuery的Ajax从后台提取数据后想把它赋值给全局变量,但是却怎么都赋不进,为什么呢? 原因其实很简单,我们用的Ajax是异步操作,也就是说在你赋值的时候数据还没提取出来,你当然赋不进去, ...

  4. Http方式下载文件

    代码: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System ...

  5. android apk 反编译过程

    一.准备必要的工具 apktool (资源文件获取) dex2jar(源码文件获取) jd-gui  (源码查看) 以上三个文件的下载地址为:https://download.csdn.net/dow ...

  6. 20.Mysql锁机制

    20.锁问题锁是计算机协调多个进程或线程并发访问某一资源的机制. 20.1 Mysql锁概述锁类型分为表级锁.页面锁.行级锁.表级锁:一个线程对表进行DML时会锁住整张表,其它线程只能读该表,如果要写 ...

  7. sqlserver自带的导入导出工具,分别导入大批量mysql和oracle数据时的感受

    sqlserver自带的导入导出工具,分别导入大批量mysql和oracle数据时,mysql经常出现格式转换出错,不好导入  导入的数据量比较大时,还不如自己写个工具导入 今天在导oracle时,想 ...

  8. 多进程copy文件

    from multiprocessing import Pool,Manager import os,time def copyFileTask(fileName,oldFolderName,newF ...

  9. Tools.Eclipse.HowToImportAnAndroidLibraryProjectIntoWorkspace

    1. File->New->Other Picture-1 2. Select "Android Project from Existing Code", and cl ...

  10. HISAT2,StringTie,Ballgown处理转录组数据

    HISAT2,StringTie,Ballgown处理转录组数据 本文总阅读量次2017-05-26 HISAT2,StringTie,Ballgown处理转录组数据思路如下: 数据质控 将RNA-s ...