```java
/**
* 打包下载文件
* @param filePath
* @param response
* @param req
*/
public void downFile(String filePath, HttpServletResponse response, HttpServletRequest req) {
response.reset();
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!filePath.endsWith(File.separator)) {
filePath = filePath + File.separator;
}
File dirFile = new File(filePath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
logger.info("下载文件失败!" + filePath + "目录不存在!");
}
//获取文件夹下的所有文件
File[] files = dirFile.listFiles();
// 设置压缩后的文件名
String zipFileName = dirFile.getName()+".zip";
OutputStream os = null;
ZipOutputStream zos = null;
BufferedInputStream bis = null;
FileInputStream in = null;
try {
// 通过response对象获取OutputStream流
os = response.getOutputStream();
// 获取zip的输出流
zos = new ZipOutputStream(os);
// 遍历文件名列表添加进压缩包
for (File file : files) {
String fileName = file.getName();
// String filePath = file.getPath();
// File file = new File(filePath);
if (file.exists()) {
// 读取文件流
in = new FileInputStream(file);
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
// 设置Content-Disposition响应头,控制浏览器弹出保存框,若没有此句浏览器会直接打开并显示文件
// 中文名要进行URLEncoder.encode编码,否则客户端能下载但名字会乱码
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
// 输入缓冲流
bis = new BufferedInputStream(in, 1024 * 10);
// 创建读写缓冲区
byte[] buf = new byte[1024 * 10];
int len = 0;
while ((len = bis.read(buf, 0, 1024 * 10)) > 0) {
// 使用OutputStream将缓冲区的数据输出到客户端浏览器
zos.write(buf, 0, len);
}
bis.close();
in.close();
zos.closeEntry();
}
}
} catch (Exception e) {
logger.error("下载文件异常:" + e.toString());
} finally {
try {
if (null != bis) {
bis.close();
}
if (null != in) {
in.close();
}
if (null != zos) {
zos.close();
}
if (null != os) {
os.close();
}
} catch (Exception e2) {
logger.error(e2.toString());
}
}
}