最近做了一个ABTest的应用,用户希望对ABTest的结果能够打包批量进行下载,这个时候就需要先对下载的多个文件进行压缩打包,再进行下载。
@RequestMapping("/download")
public Object export(HttpServletRequest request, HttpServletResponse response, @RequestParam String batchId,) throws IOException {
List<UserInfo> list = userDao.getUsers(batchId);
String tmpdir = System.getProperty("java.io.tmpdir");
if(StringUtils.isEmpty(tmpdir)){
logger.info("tmpdir is empty, use ServletContextPath");
tmpdir = request.getServletContext().getContextPath();
}
logger.info("export tmpdir:{}", tmpdir);
File tempDir = new File(tmpdir+File.separator+"download");
if(!tempDir.exists()){
boolean success = tempDir.mkdirs();
logger.info("create tempDir:{}, success:{}", tempDir.getAbsolutePath(), success);
}
File zipFile = new File(tempDir, String.format("%s.zip", batchId)); //压缩后的文件
OutputStream out = null;
InputStream in = null;
try {
convert(list, zipFile);
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
out = response.getOutputStream();
in = new FileInputStream(zipFile);
IoUtils.copy(in, out);
} catch (IOException e) {
logger.error("export file error", e);
}finally {
IoUtils.closeQuietly(out);
IoUtils.closeQuietly(in);
}
}
private void convert(List<UserInfo> list, File zipFile){
ZipOutputStream zipOut = null;
try {
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
for (UserInfo info : list){
addZipEntry(zipOut, info.getId()+".txt", info.getName()+"\t"+info.getPassword());
}
zipOut.flush();
} catch (Exception e) {
logger.error("export data failed, type:"+type+", batchId:"+batchId, e);
throw new RuntimeException("export data failed, type:"+type+", batchId:"+batchId, e);
}finally {
IoUtils.closeQuietly(zipOut);
}
}
private void addZipEntry(ZipOutputStream zipOut, String name, String data) throws IOException {
zipOut.putNextEntry(new ZipEntry(name));
zipOut.setComment("");
if(StringUtils.isEmpty(data)){
data = " ";
}
zipOut.write(data.getBytes("UTF-8"));
}