之前项目上遇到上传多个图片,一个下载按钮可以下载所有的图片,本来想多次触发下载请求,但是失败了,于是就转为合并为一个压缩包下载,下面是代码
List<Files> filesList =(List<Files>)request.getAttribute("files");
String basepath = WebUtil.formatPath(pageContext.getServletContext().getRealPath("/"));
String fileNameToClient=(String) request.getAttribute("downloadName")+"_"+ DateUtil.format(new Date(), DateUtil.yyyyMMddHHmmss);
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileNameToClient + ".rar\"");
ZipOutputStream zipout = new ZipOutputStream(response.getOutputStream());
zipout.setLevel(1);
BufferedOutputStream bos = new BufferedOutputStream(zipout);
for (int i = 0; i < filesList.size(); i++) {
Files files = filesList.get(i);
String path = files.getFileWeburl(basepath, "/web/resource");
File f = new File(path);
if (f.canRead()) {
zipout.putNextEntry(new ZipEntry(files.getSrcfilename()));
BufferedInputStream fr = new BufferedInputStream(new FileInputStream(f));
byte buffer[] = new byte[1024];
int b;
while ((b = fr.read(buffer,0,buffer.length)) != -1) zipout.write(buffer,0,b);
fr.close();
bos.flush();
}
}
bos.close();