导出 zip

		(前提 ,文件被重命名)
  1. 先下载文件到指定目录(需要压缩的)

    1. 查询所有文件
    2. 获取路径
    3. 输出目录
  2. 生成file

  3. 循环压缩下载

	/**
	 * 
	 * 此方法描述的是: 下载zip
	 * 
	 * @author: hzqq
	 * @version: 2021年10月13日 下午4:30:52
	 */
	@RequestMapping("/batchZip")
	public void batchFileToZip(HttpServletRequest request, HttpServletResponse response, String ids,String fileName) {

		try {
			
		
	            
			Assert.notNull(ids, "id must be not null !!");
			List<FileBean> fileList = fileService.getFileList(ids);// 查询数据库中记录

			String zipName = "tempFile.zip";
			if(StringUtils.isNotBlank(fileName)){
				zipName = fileName.trim().concat(".zip");
			}
			
			String userAgent = request.getHeader("User-Agent");
             
			 /*  文件的乱码处理 */
            // 针对IE或者以IE为内核的浏览器:
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            	zipName = java.net.URLEncoder.encode(zipName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
            	zipName = new String(zipName.getBytes("UTF-8"), "ISO-8859-1");
            }
	            
			List<File> createFiles = createFiles(fileList);
			response.setContentType("APPLICATION/OCTET-STREAM");
			response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
			ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
			try {
				for (Iterator<File> it = createFiles.iterator(); it.hasNext();) {
					File file = it.next();
					ZipUtils.doCompress(file.toString(), out);
					response.flushBuffer();
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}






    
	private List<File> createFiles(List<FileBean> fileList) {

		/*
		 * 1.1 查询所有文件 1.2 获取路径 1.3 输出目录
		 	数据库中 存储为 文件相对路径 ,相对于 linux or  win 系统
		 */
		String system = System.getProperty("os.name");
		String rootPath = "";
		String tempPath = "";

		List<File> files = new ArrayList<File>();
		if (system.toLowerCase().startsWith("win")) {
			rootPath = fileUploadConfig.getWinRootPath();
		} else {
			rootPath = fileUploadConfig.getLinuxRootPath();
		}
		if (system.toLowerCase().startsWith("win")) {
			tempPath = fileUploadConfig.getWinRootPathBackAllFileTemp();
		} else {
			tempPath = fileUploadConfig.getLinuxRootPathBackAllFileTemp();
		}
		// 输出到指定文件,为了更改文件名字

			// Map<String, Object> map = new HashMap<String, Object>();
		for (FileBean fileBean : fileList) {
			// generatorFileName(fileBean, map);
			generatorTempFile(rootPath, tempPath, fileBean);
			File file = new File(tempPath + File.separator + fileBean.getFileName());

			if (!file.exists()) {
				throw new RuntimeException("fiel error!" + fileBean);
			}

			files.add(file);
		}

		return files;
	}

	/**
	 * 此方法描述的是:
	 * 
	 * @author: hzqq
	 * @version: 2021年10月13日 下午5:39:33
	 */

	private void generatorTempFile(String rootPath, String tempPath, FileBean bean) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			String path = rootPath + File.separator + bean.getFilePath() + File.separator + bean.getFileEncName();
			// 最终要输出的路径
			String outPutPath = tempPath + File.separator + bean.getFileName();

			/*
			 * file.mkdirs(); // 递归创建
			 */
			// 要输出的临时文件路径 输出
			FileOutputStream fos = new FileOutputStream(outPutPath);
			// 真实存储文件的路径 读入
			bis = new BufferedInputStream(new FileInputStream(path));
			bos = new BufferedOutputStream(fos);
			// 设置3m缓存区
			int len;
			byte[] buffer = new byte[1024 * 3];
			// io
			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


/**
	 * 
	 * 此方法描述的是: 为了防止重名
	 * 
	 * @author: hzqq
	 * @version: 2021年10月19日 下午6:00:15
	 */
	public void generatorFileName(FileBean bean, Map<String, Object> map) {

		String fileOldName = bean.getFileName();
		if (StringUtils.isNotBlank(fileOldName)) {
			Object val = map.get(fileOldName);
			if (val != null) {
				Integer count = Integer.valueOf(val.toString());
				int suffix = fileOldName.lastIndexOf(".");
				bean.setFileName(fileOldName.substring(0,suffix).concat(String.valueOf(++count)).concat(fileOldName.substring(suffix,fileOldName.length())));
				map.put(fileOldName, count);
			}else{
				map.put(fileOldName,0);
			}

		}
	}

FileBean


    /**  
     * 此类描述的是:  文件实体类
     * @author: hzqq 
     * @version: 2021年10月13日 下午4:23:41   
     */
 
public class FileBean implements Serializable{
    
    private static final long serialVersionUID = -5452801884470115159L;
    
    private Integer fileId;//主键
    
    private String filePath;//文件保存路径
    
    private String fileEncName; //文件别名
    private String fileName;//文件保存名称
    
    
}



        /**  
            * 此方法描述的是:  
            * @author: hzqq  
            * @version: 2021年10月13日 下午4:54:19  
            */  
    @Select("<script>"
                + "SELECT REALNAME,  file_path filePath ,file_name  FROM tp_uploadfile  WHERE id  IN "
                + "<foreach item='item' index='index' collection='strList' open='(' separator=',' close=')'>"
                    + "#{item}"
                + "</foreach>"
            + "</script>")
    @Results(value = {  @Result(column = "filePath", property = "filePath") ,
                        @Result(column = "REALNAME", property = "fileName") ,
                        @Result(column = "file_name", property = "fileEncName")
            })
    List<FileBean> getFileList(@Param("strList") String[] res);

js

	/**
		 * 批量下载
		 */
		function btnDownload() {

			var selectrows = $("#dg").datagrid("getChecked");
			if (selectrows.length == 0) {
				$.messager.alert('提示', '请选择要下载的数据', 'warning');
				return;
			}

			for (var i = 0; i < selectrows.length; i++) {
				ids += selectrows[i].attachId + ","
			}
			postFile({
				ids: ids,
				fileName:'移交资料'
			}, href);
		}
 
		function postFile(params, url) {
			var form = document.createElement("form");
			form.style.display = "none";
			form.action = url;
			form.method = "post";
			document.body.appendChild(form);
			for (var key in params) {
				var input = document.createElement("input");
				input.type = "hidden";
				input.name = key;
				input.value = params[key];
				form.appendChild(input);
			}
			form.submit();
			form.remove();
		}

zipUtil

 
    /**  
     * 文件名:ZipUtils.java  
     *  
     * 版本信息:  
     * 日期:2021年10月13日  
     * Copyright hzqq Corporation 2021   
     * 版权所有  
     *  
     */  
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
    
    private ZipUtils(){
    }
    
    /**
     * 
         * 此方法描述的是:  
         * @author: hzqq  
         * @version: 2021年10月13日 下午4:25:50
     */
    public static void doCompress(String srcFile, String zipFile) throws IOException {
        doCompress(new File(srcFile), new File(zipFile));
    }
    
    /**
     * 文件压缩
     * @param srcFile 目录或者单个文件
     * @param zipFile 压缩后的ZIP文件
     */
    public static void doCompress(File srcFile, File zipFile) throws IOException {
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile));
            doCompress(srcFile, out);
        } catch (Exception e) {
            throw e;
        } finally {
            out.close();//记得关闭资源
        }
    }
    
    public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
        doCompress(new File(filelName), out);
    }
    
    public static void doCompress(File file, ZipOutputStream out) throws IOException{
        doCompress(file, out, "");
    }
    
    public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
        if ( inFile.isDirectory() ) {
            File[] files = inFile.listFiles();
            if (files!=null && files.length>0) {
                for (File file : files) {
                    String name = inFile.getName();
                    if (!"".equals(dir)) {
                        name = dir + "/" + name;
                    }
                    ZipUtils.doCompress(file, out, name);
                }
            }
        } else {
             ZipUtils.doZip(inFile, out, dir);
        }
    }
    
    public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
        String entryName = null;
        if (!"".equals(dir)) {
            entryName = dir + "/" + inFile.getName();
        } else {
            entryName = inFile.getName();
        }
        ZipEntry entry = new ZipEntry(entryName);
        out.putNextEntry(entry);
        
        int len = 0 ;
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(inFile);
        while ((len = fis.read(buffer)) > 0) {
            out.write(buffer, 0, len);
            out.flush();
        }
        out.closeEntry();
        fis.close();
    }

}