/**
* 写入压缩包
* file
* parentPath
*/
public void writeZip(File file, String parentPath, ZipOutputStream zos) {
if (file.exists()) { // 需要压缩的文件夹是否存在
if (file.isDirectory()) {// 是文件夹
parentPath += file.getName() + File.separator; // 文件夹名称 + "/"
File[] files = file.listFiles(); // 获取文件夹下的文件夹或文件
if (files.length != 0) {
for (File f : files) {
writeZip(f, parentPath, zos);
}
} else { // 空目录则创建当前目录
try {
zos.putNextEntry(new ZipEntry(parentPath));
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
} else { //是文件
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
nameStr = parentPath + file.getName();
ZipEntry ze = new ZipEntry(nameStr);
zos.putNextEntry(ze);
byte[] content = new byte[1024];
int len;
while ((len = fis.read(content)) != -1) {
zos.write(content, 0, len);
zos.flush();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
}
/**
* @param request
* @param response
* 下载目录
*/
@RequestMapping("/doc/DocAction!downLoadFolderZip.action")
public void downLoadFolderZip(HttpServletRequest request, HttpServletResponse response){
String zipName = "";// 定义压缩包名称
FileOutputStream fos = null;
ZipOutputStream zos = null;
OutputStream out = null;
try{
String docId = request.getParameter("docId");
//查询当前要下载的目录,这里是我的业务数据doc,通过doc拿到下载路径
DocInfoVo vo = new DocInfoVo();
vo.setDocId(docId);
DocInfoVo doc = docInfoService.queryDocInfoVo(vo);
//下载地址
String configPath = ReadConfigUtils.getConfigValueUpFilePath("sharedoc")+"/"; //这是配置文件配置的地址
String docPath = doc.getMuluIdPath().replaceAll("\\|", Matcher.quoteReplacement(File.separator));//转义一下,目录在磁盘的位置
if(StringUtils.isNotBlank(configPath) && StringUtils.isNotBlank(docPath)){
zipName = doc.getDocName()+".zip";//下载的zip名称
File zipFile = new File(zipName);
try {
File files = new File(configPath + docPath);
fos = new FileOutputStream(zipName);
zos = new ZipOutputStream(fos);
writeZip(files, "", zos);
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} finally {
if(zos != null){
zos.close();//这里关闭ZipOutputStream,不会出现解压文件文件末端出错的问题
}
}
try {
out = response.getOutputStream();
response.reset();
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(zipName.getBytes("GB2312"), "ISO-8859-1"));
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("UTF-8");
out.write(FileUtils.readFileToByteArray(zipFile));
out.flush();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}finally{
if(fos != null){
fos.close();
}
if(out != null){
out.close();
}
}
}
}catch(Exception e){
logger.error(e.getMessage(),e);
}
}
注明:部分代码是从其他博客那复制的,原文链接忘了,请见谅;