java 多文件压缩下载

1.前台页面通过ajax将所选属性,以json格式传递到后台
例如:    var obje={
            attribute1:value,
            attribute2:value,
            ...
        }
        $.ajax({  
            type: "post",
            url: "后台处理数据地址/functionName",
            data:obje,
            dataType : "json",
            async:true,
            success: function(data){
                
            },
            error:function(e) {}
        });
其中 obje中的属性,最好和后台接收实体中一一对应,方便处理(直接get就可获取),否则就要使用@RequestParam(required= false)String attribute1来接收参数
2.后台处理数据
    @RequestMapping(value = {"functionName"})
    @ResponseBody
    public String functionName(ShiTiName shiTiName, Model model,@RequestParam(required= false)String attribute1,
        @RequestParam(required= false)String attribute2) {//attribute1、attribute2不包含实体属性中
        //生成的附件保存地址attachmentPath
        String attachmentPath = getFileAttachmentPath();
        String fileName="附件"+DateUtils.getDate("yyyyMMddHHmmss");
        attachmentPath =attachmentPath+fileName;
        String tag="0";//默认成功
        //获取服务器端文件存储的根路径
        String paths=getUploadPath();
        try {
            //根据前端传递参数,获取符合条件的所有数据
            List<ShiTiName> list = shiTiNameService.getPersonInfoList(shiTiName);
            for (int i = 0; i < list.size(); i++) {
                String path=attachmentPath+"/"+list.get(i).getName()+"/";
                File file1  = new File(path);
                if(!file1.exists()){//如果文件夹不存在则生成
                    File files = new File(path);
                    files.setWritable(true, false); //linux创建文件路径授权
                    boolean flg =files.mkdirs();
                    if(flg){
                        //System.out.println("成功生成文件夹:"+path);
                    }
                }
                //所选属性 split
                String[] split = shiTiName.getDaoChuXiangStrs().split(",");
                //将前台所选属性 对应的文件,复制到要压缩的文件夹中
                for (int j = 0; j < split.length; j++) {
                    if(split[j].equals("1")) {//第一个所选属性
                        //paths服务器端文件存储的根路径
                        //path要压缩的文件夹
                        //list.get(i).getAttribute1()所选属性对应的文件地址
                        getCopyPath(paths,path,list.get(i).getAttribute1());
                    }else if(split[j].equals("2")) {//第二个所选属性
                        getCopyPath(paths,path,list.get(i).getAttribute2());
                    }...
                }
            }
            //前台所选属性,对应的文件,都已复制到path对应的文件夹中,然后将文件夹压缩
            zipFiles(attachmentPath,"",attachmentPath+".zip");
        } catch (IOException e) {
            e.printStackTrace();
            tag=1;//异常失败
            //将生成的文件夹删除
            File fileDir  = new File(attachmentPath);
            if(fileDir.exists()) {
                deleteDirectory(attachmentPath);
            }
            
            File file  = new File(attachmentPath+".zip");
            if(file.isFile()) {
                delFile(attachmentPath+".zip");
            }
        } finally {
            //压缩完成,将生成的文件夹删除
            File fileDir  = new File(attachmentPath);
            if(fileDir.exists()) {
                deleteDirectory(attachmentPath);
            }
        }
        return tag;
    }        
    public String getSysPath() {
        String path = Thread.currentThread().getContextClassLoader()
                .getResource("").toString();
        String temp = path.replaceFirst("file:/", "").replaceFirst(
                "WEB-INF/classes/", "");
        String separator = System.getProperty("file.separator");
        String resultPath = temp.replaceAll("/", separator + separator);
        return resultPath;
    }
    //附件保存路径
    public String getFileAttachmentPath() {
        String finallstsr=SystemPath.getSysPath();
               finallstsr = finallstsr.replaceAll("\\", "/");
        String proRootPath="/"+finallstsr+"userfiles/attachment/";//Linux路径
        
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            proRootPath=SystemPath.getSysPath()+"userfiles\attachment\";//Windows路径
        }
        return proRootPath;
    }
    //上传下载路径
    public String getUploadPath() {
        String finallstsr=SystemPath.getSysPath();
               finallstsr = finallstsr.replaceAll("\\", "/");
        String proRootPath="/"+finallstsr+"userfiles";//Linux路径
        
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            proRootPath=SystemPath.getSysPath()+"\userfiles";//Windows路径
        }
        return proRootPath;
    }
    
    //paths服务器端文件存储的根路径
    //path要压缩的文件夹
    //filePath所选属性对应的文件地址
    private void getCopyPath(String paths,String path,String filePath) throws IOException {
        if (filePath !=null && !filePath.equals("")) {
            if(filePath.indexOf(",")>0) {
                String[] split = filePath.split(",");
                for (String string : split) {
                    File file=new File(paths+"/"+string);
                    if(file.isFile()) {
                        String fileName = string.split("/")[1].substring(13);
                        File fileCopyPath=new File(path+fileName);
                        FileUtils.copyFile(file,fileCopyPath);
                    }
                }
            }else {
                File file=new File(paths+"/"+filePath);
                if(file.isFile()) {
                    File fileCopyPath=new File(path+filePath.split("/")[1].substring(13));
                    FileUtils.copyFile(file,fileCopyPath);
                }
            }
        }
    }
    /**
     * 压缩文件或目录
     * @param srcDirName 压缩的根目录
     * @param fileName 根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
     * @param descFileName 目标zip文件
     */
    public void zipFiles(String srcDirName, String fileName,String descFileName) {
        // 判断目录是否存在
        if (srcDirName == null) {
            logger.debug("文件压缩失败,目录 " + srcDirName + " 不存在!");
            return;
        }
        File fileDir = new File(srcDirName);
        if (!fileDir.exists() || !fileDir.isDirectory()) {
            logger.debug("文件压缩失败,目录 " + srcDirName + " 不存在!");
            return;
        }
        String dirPath = fileDir.getAbsolutePath();
        File descFile = new File(descFileName);
        try {
            ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
            zouts.setEncoding("GBK");
            if ("*".equals(fileName) || "".equals(fileName)) {
                FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
            } else {
                File file = new File(fileDir, fileName);
                if (file.isFile()) {
                    FileUtils.zipFilesToZipFile(dirPath, file, zouts);
                } else {
                    FileUtils
                            .zipDirectoryToZipFile(dirPath, file, zouts);
                }
            }
            zouts.close();
            logger.debug(descFileName + " 文件压缩成功!");
        } catch (Exception e) {
            logger.debug("文件压缩失败:" + e.getMessage());
            e.printStackTrace();
        }

    }
    /**
     * 将目录压缩到ZIP输出流
     * @param dirPath 目录路径
     * @param fileDir 文件信息
     * @param zouts 输出流
     */
    public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
        if (fileDir.isDirectory()) {
            File[] files = fileDir.listFiles();
            // 空的文件夹
            if (files.length == 0) {
                // 目录信息
                ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
                //entry.setUnixMode(755);
                try {
                    zouts.putNextEntry(entry);
                    zouts.closeEntry();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }

            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    // 如果是文件,则调用文件压缩方法
                    FileUtils
                            .zipFilesToZipFile(dirPath, files[i], zouts);
                } else {
                    // 如果是目录,则递归调用
                    FileUtils.zipDirectoryToZipFile(dirPath, files[i],
                            zouts);
                }
            }
        }
    }
    /**
     * 将文件压缩到ZIP输出流
     * @param dirPath 目录路径
     * @param file 文件
     * @param zouts 输出流
     */
    public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
        FileInputStream fin = null;
        ZipEntry entry = null;
        // 创建复制缓冲区
        byte[] buf = new byte[4096];
        int readByte = 0;
        if (file.isFile()) {
            try {
                // 创建一个文件输入流
                fin = new FileInputStream(file);
                // 创建一个ZipEntry
                entry = new ZipEntry(getEntryName(dirPath, file));
                //entry.setUnixMode(644);
                // 存储信息到压缩文件
                zouts.putNextEntry(entry);
                // 复制字节到压缩文件
                while ((readByte = fin.read(buf)) != -1) {
                    zouts.write(buf, 0, readByte);
                }
                zouts.closeEntry();
                fin.close();
                System.out
                        .println("添加文件 " + file.getAbsolutePath() + " 到zip文件中!");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名
     * @param dirPat 目录名
     * @param file entry文件名
     * @return
     */
    private static String getEntryName(String dirPath, File file) {
        String dirPaths = dirPath;
        if (!dirPaths.endsWith(File.separator)) {
            dirPaths = dirPaths + File.separator;
        }
        String filePath = file.getAbsolutePath();
        // 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
        if (file.isDirectory()) {
            filePath += "/";
        }
        int index = filePath.indexOf(dirPaths);

        return filePath.substring(index + dirPaths.length());
    }
    
    /**
     * 
     * 删除目录及目录下的文件
     * 
     * @param dirName 被删除的目录所在的文件路径
     * @return 如果目录删除成功,则返回true,否则返回false
     */
    public static boolean deleteDirectory(String dirName) {
        String dirNames = dirName;
        if (!dirNames.endsWith(File.separator)) {
            dirNames = dirNames + File.separator;
        }
        File dirFile = new File(dirNames);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            logger.debug(dirNames + " 目录不存在!");
            return true;
        }
        boolean flag = true;
        // 列出全部文件及子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                // 如果删除文件失败,则退出循环
                if (!flag) {
                    break;
                }
            }else if (files[i].isDirectory()) {// 删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                // 如果删除子目录失败,则退出循环
                if (!flag) {
                    break;
                }
            }
        }

        if (!flag) {
            logger.debug("删除目录失败!");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            logger.debug("删除目录 " + dirName + " 成功!");
            return true;
        } else {
            logger.debug("删除目录 " + dirName + " 失败!");
            return false;
        }
    }
    
    /**
     * 
     * 删除单个文件
     * 
     * @param fileName 被删除的文件名
     * @return 如果删除成功,则返回true,否则返回false
     */
    public boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                logger.debug("删除文件 " + fileName + " 成功!");
                return true;
            } else {
                logger.debug("删除文件 " + fileName + " 失败!");
                return false;
            }
        } else {
            logger.debug(fileName + " 文件不存在!");
            return true;
        }
    }
    /**
     * 
     * 删除文件,可以删除单个文件或文件夹
     * 
     * @param fileName 被删除的文件名
     * @return 如果删除成功,则返回true,否是返回false
     */
    public boolean delFile(String fileName) {
         File file = new File(fileName);
        if (!file.exists()) {
            logger.debug(fileName + " 文件不存在!");
            return true;
        } else {
            if (file.isFile()) {
                return deleteFile(fileName);
            } else {
                return deleteDirectory(fileName);
            }
        }
    }
原文地址:https://www.cnblogs.com/ljc1212/p/14845137.html