多个文件,目录不同,通过条件查询如何进行打包下载呢?
1.利用ZipEntry进i行文件的压缩
2.前台jsp传入需要打包下载的一系列的文件的路径(数组类型)。因为是在checkBox中,表单提交会自动将其定义成数组。只需要将name名称命名成后台需要得到的路径数组名称
比如前台
downLoadZip.jsp
--------checkBox处代码-------------------------------
利用iterator迭代出来的filePath
<input type="checkbox" name="downLoadPaths"
value='<s:property value="filePath"/>'/>
后台Action
private String[] downLoadPaths;
对downLoadPaths进行遍历,打包。。。。
代码:
/**
* 批量下载(压缩成zip,然后下载)。不创建临时文件
*
* @author Cloudy
*
*/
@Namespace("xxxxxx")
public class DownZipAction {
/**
*
*/
private static final long serialVersionUID = 1L;
// 传递一个List<String>()对象传值路径合集
private String[] downLoadPaths;
private OutputStream res;
private ZipOutputStream zos;
private String outPath;
// Action主方法
@Action(value="DownLoadZip",results={@Result(name="nodata",location="/error.jsp"),
@Result(name="success",location="xxxx.jsp")})
public String downLoadZip() throws Exception {
// 有数据可以下载
if (downLoadPaths.length != 0) {
// 进行预处理
preProcess();
} else {
// 没有文件可以下载,返回nodata
return "nodata";
}
// 处理
writeZip(downLoadPaths);
// 后处理关闭流
afterProcess();
return SUCCESS;
}
// 压缩处理
public void writeZip(String[] downLoadPaths) throws IOException {
byte[] buf = new byte[8192];
int len;
for (String filename : downLoadPaths) {
File file = new File(filename);
if (!file.isFile())
continue;
ZipEntry ze = new ZipEntry(file.getName()); //apache jar的ZipEntry
zos.putNextEntry(ze);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
while ((len = bis.read(buf)) > 0) {
zos.write(buf, 0, len);
}
bis.close();
zos.closeEntry();
}
}
// 预处理
public void preProcess() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
res = response.getOutputStream();
// 清空输出流(在迅雷下载不会出现一长窜)
response.reset();
// 设定输出文件头
response.setHeader("Content-Disposition", "attachment;filename=document.zip");
response.setContentType("application/zip");
zos = new ZipOutputStream(res);
}
// 后处理
public void afterProcess() throws IOException {
zos.close();
res.close();
}
public OutputStream getRes() {
return res;
}
public void setRes(OutputStream res) {
this.res = res;
}
public ZipOutputStream getZos() {
return zos;
}
public void setZos(ZipOutputStream zos) {
this.zos = zos;
}
public String[] getDownLoadPaths() {
return downLoadPaths;
}
public void setDownLoadPaths(String[] downLoadPaths) {
this.downLoadPaths = downLoadPaths;
}
public String getOutPath() {
return outPath;
}
public void setOutPath(String outPath) {
this.outPath = outPath;
}
}