JAVA实现多个PDF文件压缩下载
@RequestMapping(params = "batchExports")
public void batchExportPDFs(HttpServletRequest req, HttpServletResponse resp) throws IOException, DocumentException {
//获取各个文件路径
List<String> files = new ArrayList<>();
//json转list
List<Map<String, String>> list = (List<Map<String, String>>) JSONArray.parse(req.getParameter("ids"));
//遍历list,返回文件
for (Map<String, String> map : list) {
String path = exportPDF(req,map.get("caseId"), map.get("did"));
files.add(path);
}
//创建压缩文件需要的空的zip包
String zipBasePath= req.getSession().getServletContext().getRealPath("/upload/zip");
String zipName = "退保申请审批表"+getDateString()+".zip";
String zipFilePath = zipBasePath+File.separator+zipName;
//压缩文件
File zip = new File(zipFilePath);
if (!zip.exists()){
zip.createNewFile();
}
//创建zip文件输出流
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
this.zipFile(zipBasePath,zipName, zipFilePath,files,zos);
zos.close();
resp.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
//将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buff = new byte[bis.available()];
bis.read(buff);
bis.close();
// 清空response
resp.reset();
// 设置response的Header
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "UTF-8"));
OutputStream out = resp.getOutputStream();
out.write(buff);//输出数据文件
out.flush();//释放缓存
out.close();//关闭输出流
}
/**
* 压缩文件
* @param zipBasePath 临时压缩文件基础路径
* @param zipName 临时压缩文件名称
* @param zipFilePath 临时压缩文件完整路径
* @param filePaths 需要压缩的文件路径集合
* @throws IOException
*/
private String zipFile(String zipBasePath, String zipName, String zipFilePath, List<String> filePaths,ZipOutputStream zos) throws IOException {
//循环读取文件路径集合,获取每一个文件的路径
for(String filePath : filePaths){
File inputFile = new File(filePath); //根据文件路径创建文件
if(inputFile.exists()) { //判断文件是否存在
if (inputFile.isFile()) { //判断是否属于文件,还是文件夹
//创建输入流读取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
//将文件写入zip内,即将文件进行打包
zos.putNextEntry(new ZipEntry(inputFile.getName()));
//写入文件的方法,同上
int size = 0;
byte[] buffer = new byte[1024]; //设置读取数据缓存大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
//关闭输入输出流
zos.closeEntry();
bis.close();
} else { //如果是文件夹,则使用穷举的方法获取文件,写入zip
try {
File[] files = inputFile.listFiles();
List<String> filePathsTem = new ArrayList<String>();
for (File fileTem:files) {
filePathsTem.add(fileTem.toString());
}
return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem,zos);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return null;
}
参考: 其他.