当前服务器多文件压缩下载实现
@ApiOperation("导出资料多个")
@RequestMapping(value = "/infoexportfiles", method = {RequestMethod.GET, RequestMethod.POST})
public void infoexportfiles(HttpServletResponse res,@ApiParam(value = "任务id")@RequestParam(value = "ids") String ids) {
try {
List<JSONObject> infoList = getInfoList(ids);
if (infoList.size() > 0) {
List<JSONObject> list = new ArrayList<>();
for (JSONObject info : infoList) {
String path = info.getString("path");
if(StringUtils.isNotEmpty(path)){
String filename = info.getString("filename");
JSONObject jb = new JSONObject();
jb.put("name",filename);
jb.put("path",path);
list.add(jb);
}
}
//创建压缩文件需要的空的zip包
String zipName = "resources.zip";
String zipFilePath = taskpath+File.separator+zipName;
//压缩文件
File zip = new File(zipFilePath);
if (!zip.exists()){
zip.createNewFile();
}
//创建zip文件输出流
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
zipFile(taskpath,zipName, zipFilePath,list,zos);
zos.close();
res.setCharacterEncoding("UTF-8"); //设置编码字符
res.setContentType("application/octet-stream;charset=UTF-8"); //设置下载内容类型
res.setHeader("Content-disposition", "attachment;filename="+zipName);//设置下载的压缩文件名称
OutputStream out = res.getOutputStream(); //创建页面返回方式为输出流,会自动弹出下载框
//将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
byte[] buff = new byte[bis.available()];
bis.read(buff);
bis.close();
out.write(buff);//输出数据文件
out.flush();//释放缓存
out.close();//关闭输出流
}
}catch(Exception e) {
e.printStackTrace();
}
}
/**
* 压缩文件
* @param zipBasePath 临时压缩文件基础路径
* @param zipName 临时压缩文件名称
* @param zipFilePath 临时压缩文件完整路径
* @param list 需要压缩的文件路径集合
* @throws IOException
*/
private String zipFile(String zipBasePath, String zipName, String zipFilePath, List<JSONObject> list,ZipOutputStream zos) throws IOException {
log.info("压缩文件");
//循环读取文件路径集合,获取每一个文件的路径
Map<String,String> map = new HashMap<>();
for(JSONObject filePath : list){
File inputFile = new File(filePath.getString("path")); //根据文件路径创建文件
if(inputFile.exists()) { //判断文件是否存在
if (inputFile.isFile()) { //判断是否属于文件,还是文件夹
//创建输入流读取文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
//将文件写入zip内,即将文件进行打包
String name = filePath.getString("name");
if(map.containsKey(name)){
name = name.substring(0,name.indexOf(".")) +System.currentTimeMillis()+ name.substring(name.indexOf("."));
}
map.put(name,"0");
zos.putNextEntry(new ZipEntry(name));
//写入文件的方法,同上
int size = 0;
byte[] buffer = new byte[1024]; //设置读取数据缓存大小
while ((size = bis.read(buffer)) > 0) {
zos.write(buffer, 0, size);
}
//关闭输入输出流
zos.closeEntry();
bis.close();
}
}
}
return null;
}