public ActionForward batchDownLoad(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String id=request.getParameter("id");
//根据自己实际数据取值 此处我的数据:[[文件全名称,文件路径,将要使用的名称,...],...]
List<Object[]> list= getService().getFiles( id);
if(list.size()==0){
response.getWriter().write("<div style='text-align:center;color:red'>未能找到可下载的文件!</div>");
return null;
}
File baseFolder = new File("\\zip");//zip文件目录
if(!baseFolder.exists()){//没有就创建
baseFolder.mkdirs();
}else{//删除6个月前的文件
Date willDelDate=DateUtils.addMonth(new Date(), -6);//将要删除的时间(6个月前)
File[] fileList =baseFolder.listFiles();
for(File f:fileList){
if(f.isDirectory()){continue;}//只删此目录中的文件 其下文件夹不管
Date fileDate=DateUtils.parse(f.getName().split("\\.")[0],"yyyyMMddHHmmss");
if(fileDate!=null && fileDate.before(willDelDate)){
f.delete();
}
}
}
String zipFileName=DateUtils.format(DateUtils.getNow(), "yyyyMMddHHmmss")+".zip";//压缩包的文件名称
FileOutputStream outputStream=new FileOutputStream(baseFolder+"\\"+zipFileName);
ZipOutputStream zipOutputStream=new ZipOutputStream(new BufferedOutputStream(outputStream));;
FileInputStream inputStream=null;
FileInputStream zipInput=null;
OutputStream os = null;
ByteArrayOutputStream arrayOutputStream=null;
try {
List<String> nameList=new ArrayList<>();
byte[] buff=new byte[1024];//每次读完缓存的字节
for(Object[] arr:list){//将元素装到zipOutputStream
String suffix=arr[0].toString().split("\\.")[1];//文件后缀
String name=(arr[2].toString())+"."+suffix;//元素文件全名
int i=1;
while(nameList.contains(name)){//有重复的名字时 在后面加(i)
name=(arr[2].toString())+"("+i+")."+suffix;
i++;
}
nameList.add(name);
File file=new File(SoftwareDirectory.FILE_DATA_MT3_HOME+"\\"+arr[1].toString());//压缩文件
inputStream=new FileInputStream(file);
zipOutputStream.putNextEntry(new ZipEntry(name));
//zipOutputStream.setComment("hello");//压缩文件的注释
int temp=0;
while((temp=inputStream.read(buff))!=-1){
zipOutputStream.write(buff,0,temp);
}
IOUtils.close(inputStream);
}
IOUtils.close(zipOutputStream);
File zipFile=new File(baseFolder+"\\"+zipFileName);
zipInput=new FileInputStream(zipFile);
arrayOutputStream=new ByteArrayOutputStream();
int temp2=0;
while((temp2=zipInput.read(buff))!=-1){
arrayOutputStream.write(buff,0,temp2);
}
byte[]data=arrayOutputStream.toByteArray();
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.toUtf8(zipFileName));
response.setContentLength(NumberUtils.toInteger(zipFile.length(),0));
response.setContentType("application/x-msdownload");
os = response.getOutputStream();
FileCopyUtils.copy(data, os);
} finally{
IOUtils.close(zipInput,os,arrayOutputStream);//关闭多个流
}
return null;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交