struts2下载文件功能(边下载边打包)

多个文件,目录不同,通过条件查询如何进行打包下载呢?

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; } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值