最近做了一些有关批量压缩下载的功能,网上也找了一些资源,但都不是太全面,所以自己整理一份,已备不时之需。

直接上代码:

  // 获取项目路径
  private static String WEBCLASS_PATH = Thread.currentThread().getContextClassLoader().getResource("").getPath();
  // 获取webinf路径
  private static String WEBINF_PATH = WEBCLASS_PATH.substring(0, WEBCLASS_PATH.lastIndexOf("classes"));
  // 获取upload路径
  private static String UPLOAD_PATH = WEBINF_PATH.substring(0, WEBINF_PATH.lastIndexOf("WEB-INF")) + "upload/";

 public void downloadAllFiles(HttpServletRequest request, HttpServletResponse response) {
// 获取要下载的文件对应的信息ID-选中文件ID拼接的字符串
String lessionIdStr = request.getParameter("fileIds");
// 第一个文件的文件名
String firstFileName = "";
List<UploadFileInfo> downLoadFiles = new LinkedList<UploadFileInfo>();
if (StringUtil.isNotEmpty(lessionIdStr)) {
int end = lessionIdStr.lastIndexOf(",");
if (end > 0) {
if (end == lessionIdStr.length() - 1) {
lessionIdStr = lessionIdStr.substring(0, end);
}
String[] ids = lessionIdStr.split(",");
for (int i = 0; i < ids.length; i++) {
// 循环获取每一个文件信息
UploadFileInfo fileInfo = uploadFileInfoService.selectByPrimaryKey(ids[i]);
if (fileInfo != null) {
downLoadFiles.add(fileInfo);
}
if (i == 0) {
firstFileName = fileInfo.getFileName().substring(0, fileInfo.getFileName().lastIndexOf("."));
}
}
}else {
// 循环获取每一个文件信息
UploadFileInfo fileInfo = uploadFileInfoService.selectByPrimaryKey(lessionIdStr);
if (fileInfo != null) {
downLoadFiles.add(fileInfo);
}
firstFileName = fileInfo.getFileName().substring(0, fileInfo.getFileName().lastIndexOf("."));
}
} // 有数据可以下载
if (downLoadFiles.size() != 0) {
// 进行预处理
preProcess(firstFileName, response);
// 压缩处理
writeZip(downLoadFiles);
// 下载文件
downFile(response);
// 删除临时压缩文件
afterProcess();
}
} // 压缩文件输出流
private ZipOutputStream out;
// 临时压缩文件存储路径
private String filePath; /**
* 描述: 预处理
* 参数: @param firseFileName 批量下载的第一个文件名
* 参数: @param response
*/
private void preProcess(String firseFileName, HttpServletResponse response) {
// 压缩文件名称
String zipName = "【批量下载】" + firseFileName + "等.zip";
filePath = UPLOAD_PATH + zipName;
try {
// 初始化压缩文件输出流
out = new ZipOutputStream(new FileOutputStream(filePath));
// 清空输出流(在迅雷下载不会出现一长窜)
response.reset();
//设置响应头和客户端保存文件名
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
// !!!new String(zipName.getBytes("GBK"), "8859_1") 如果文件包含中文,必须进行转换,否则下载后的文件名是乱码格式的
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(zipName.getBytes("GBK"), "8859_1"));
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 描述: 压缩处理
* 参数: @param downloadFiles 批量下载的文件数据集合
*/
private void writeZip(List<UploadFileInfo> downloadFiles) {
byte[] buf = new byte[2048];
int len = 0;
try {
for (UploadFileInfo fileInfo : downloadFiles) {
// 获取上传文件
File file = new File(UPLOAD_PATH.substring(0, UPLOAD_PATH.lastIndexOf("upload")) + fileInfo.getFilePath());
if (!file.isFile()) {
continue;
}
// 设置编码
out.setEncoding(System.getProperty("sun.jnu.encoding"));
// 设置压缩文件名称
ZipEntry ze = new ZipEntry(fileInfo.getFileName());
// 加入到输出流中
out.putNextEntry(ze);
// 对源文件进行读取并输出
FileInputStream fis = new FileInputStream(file);
while ((len = fis.read(buf)) != -1) {
out.write(buf, 0, len);
}
// 刷新(必须要有)
out.flush();
out.closeEntry();
fis.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 描述: 下载临时压缩文件
* 参数: @param response
*/
private void downFile(HttpServletResponse response) {
try {
File file = new File(filePath);
if (file.exists()) {
InputStream ins = new FileInputStream(filePath);
// 放到缓冲流里面
BufferedInputStream bins = new BufferedInputStream(ins);
// 获取文件输出IO流
OutputStream outs = response.getOutputStream();
BufferedOutputStream bouts = new BufferedOutputStream(outs);
int bytesRead = 0;
byte[] buffer = new byte[1024];
// 开始向网络传输文件流
while ((bytesRead = bins.read(buffer)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
// 这里一定要调用flush()方法
bouts.flush();
ins.close();
bins.close();
outs.close();
bouts.close();
}
} catch (IOException e) {
logger.error("文件下载出错", e);
}
} /**
* 描述: 删除临时压缩文件
*/
private void afterProcess() {
// 删除源文件
File tempZip=new File(filePath);
if(tempZip.exists()) {
tempZip.delete();
}
}
05-07 15:50