JAVA实现文件批量打包下载
实现
1.打包工具类的实现
/**
* @author zhouxuan
* @since 2019/4/19
*/
public class ZipUtils {
/**
* @author zhouxuan
* @since 2019/4/19
*/
public class ZipUtils {
/**
* 批量打包
*
* @param jsonString json格式字符串数据
* @param fileSaveRootPath 项目根目录
* @return zip文件保存绝对路径
*/
public String createZipAndReturnPath(String jsonString, String fileSaveRootPath) {
//生成jsonArray列表
JSONArray jsonArray = JSONArray.fromObject(jsonString);
try {
//生成打包下载后的zip文件:Papers.zip
String papersZipName = "Papers.zip";
//zip文件保存路径
String zipPath = fileSaveRootPath + papersZipName;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
//遍历jsonArray列表获取所有JSONObject对象
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//获得文件相对路径
String relativePath = jsonObject.getString("file_Path");
//获得文件名
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;
}
}
2.zip文件包的下载
/**
* 批量下载
* @param request 请求
* @param response 返回
*/
public void batchDownloadFiles(HttpServletRequest request,HttpServletResponse response) {
//读取前端传来json字段
String jsonString = request.getParameter("paperInfo");
//获取web项目根目录
String fileSaveRootPath = request.getSession().getServletContext().getRealPath("/");
//创建zip文件并返回zip文件路径
String zipPath = new ZipUtils().createZipAndReturnPath(jsonString, fileSaveRootPath);
try {
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/zip;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=Papers.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();
}
}