打包zip工具类
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
/**
* 批量打包
*
* @param fileSaveRootPath 项目根目录
* @return zip文件保存绝对路径
*/
public String createZipAndReturnPath(List> list,String filename, String fileSaveRootPath) {
try {
//生成打包下载后的zip文件:文件名.zip
String papersZipName = filename+".zip";
//zip文件保存路径
String zipPath = fileSaveRootPath + papersZipName;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
//遍历jsonArray列表获取所有JSONObject对象
for (int i = 0; i < list.size(); i++) {
Mapmap=list.get(i);
//获得文件相对路径
String relativePath = map.get("filepath").toString();
//获得文件名
String fileName = relativePath.substring(relativePath.lastIndexOf("/")+1);
//获得下载文件完整路径
String downloadPath = fileSaveRootPath + relativePath;
//以论文标题为每个文件命名
FileInputStream fis = new FileInputStream(downloadPath);
out.putNextEntry(new ZipEntry(fileName));
//写入压缩包
int len;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
out.flush();
return zipPath;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 批量下载
* @param request 请求
* @param response 返回
*/
public void batchDownloadFiles(List> list,String filename,HttpServletRequest request, HttpServletResponse response) {
//获取web项目根目录
String fileSaveRootPath = request.getSession().getServletContext().getRealPath("/");
//创建zip文件并返回zip文件路径
String zipPath = new ZipUtils().createZipAndReturnPath(list, filename,fileSaveRootPath);
try {
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/zip;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="+filename+".zip");
System.out.println(response.getHeader("Content-Disposition"));
//开始下载
BufferedInputStream is = new BufferedInputStream(new FileInputStream(new File(zipPath)));
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[1024];
int len = 0;
while ((len = is.read(buff, 0, buff.length)) != -1) {
out.write(buff, 0, len);
}
out.close();
out.flush();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
controller层
//附件批量下载并打包
@RequestMapping(value = "fileBatchDownload", method = RequestMethod.GET)
public void fileBatchDownload(HttpServletRequest request,HttpServletResponse response){
String id=request.getParameter("id"); //前端传的主表id
String filename=request.getParameter("filename"); //压缩包名称
List> list=busAnnexMService.fileBatchDownload(id); //查询id下的所有附件信息
new ZipUtils().batchDownloadFiles(list,filename,request,response); //调用工具类打包并下载
}