Struts2 动态压缩成zip文件下载

fmms 12年前
     功能:文件下载    <br /> 简述:    <br /> 1.根据画面上的复选框进行文件打包下载    <br /> 2.待下载文件保存在服务器的硬盘上,打包过程中不生成临时文件    <br /> 3.打包过程中需要动态创建一个txt文件一并打进zip包中    <br /> 4.页面上没有文件被选择的场合,按下【下载】按钮后,什么都不做(不刷新页面)    <br />    <br /> 部分内容参考自互联网,如果错误,欢迎指正。    <br />    <br /> Struts配置文件    <br />    <pre class="brush:xml; toolbar: true; auto-links: false;"> <!-- 数据下载Action --> <action name="downloadWaveData" class="DownloadAction">  <result name="nodata" type="httpheader">   <param name="status">204</param>  </result> </action></pre>    <br />    <br /> Action代码    <br />    <pre class="brush:java; toolbar: true; auto-links: false;"> private OutputStream res;  private ZipOutputStream zos;   // action的主方法  public String execute() throws Exception {       if (有数据可下载) {;    // 预处理    preProcess();    } else {    // 没有文件可下载的场合,返回nodata,设定参照struts配置文件    return "nodata";   }    // 在这里编辑好需要下载的数据   // 文件可以是硬盘上的   // 文件也可以是自己写得数据流,如果是自己写得数据流,请参看outputZipFile方法中的【2.】   File file = new File();   file = ...   outputZipFile(file);      // 后处理   afterProcess();      return null;    }   // 预处理  public void preProcess() throws Exception {      HttpServletResponse response = ServletActionContext.getResponse();      res = response.getOutputStream();    //清空输出流    response.reset();       //设定输出文件头    response.setHeader("Content-disposition ","attachment; filename=a.zip ");      response.setContentType("application/zip");   zos = new ZipOutputStream(res);     }   // 后处理  public void afterProcess() throws Exception {   zos.close();   res.close();  }   // 写文件到客户端  private void outputZipFile(File file) throws IOException, FileNotFoundException {   ZipEntry ze = null;   byte[] buf = new byte[1024];      int readLen = 0;      File file = (File)fileList.get(i);      // 1.动态压缩一个File到zip中   // 创建一个ZipEntry,并设置Name和其它的一些属性   // 压缩包中的路径和文件名称   ze = new ZipEntry("1\\1" + f.getName());   ze.setSize(file.length());   ze.setTime(file.lastModified());    // 将ZipEntry加到zos中,再写入实际的文件内容   zos.putNextEntry(ze);   InputStream is = new BufferedInputStream(new FileInputStream(file));    // 把数据写入到客户端   while ((readLen = is.read(buf, 0, 1024)) != -1) {    zos.write(buf, 0, readLen);   }   is.close();      // 2.动态压缩一个String到zip中   String customFile = "This is a text file.";    // 压缩包中的路径和文件名称   ZipEntry cze = new ZipEntry(“1\\1\\” + "Test.txt");   zos.putNextEntry(cze);    // 利用ByteArrayInputStream把流数据写入到客户端   is = new ByteArrayInputStream(customFile.getBytes());   while ((readLen = is.read(buf, 0, 1024)) != -1) {    zos.write(buf, 0, readLen);   }     }</pre>    <br /> 转自:    <a href="/misc/goto?guid=4959500518411297764" target="_blank">http://tjmljw.iteye.com/blog/1338598</a>