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

网上看了很多,本文使用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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值