struts2 批量下载(转载)

来源:互联网 发布:安装越狱软件 编辑:程序博客网 时间:2024/05/17 08:34

设计思路:前台jsp页面form 传参传文件路径,多文件的话,将这些文件路径用分隔符拼接,后台分割这些文件路径,然后将这些文件路径下的文件打包,然后在下载。总体来说三步走,上传文件(路径),文件打包,下载。

思路出来了,代码如下仅供参考:

要下载作业下文件目录显示:

public ActionForward JobIdFileList(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response) {
  System.out.println("zyFileList");
  Userinfo userinfo =(Userinfo)request.getSession().getAttribute("userinfo");
//  if(userinfo == null){
//   return null;
//  }
  String strpath = this.getServlet().getServletContext().getRealPath("uploadfile")+"//"+request.getParameter("projectName")+"//"+request.getParameter("JobId");
  System.out.println("dir============="+strpath);
  //ArrayList<String> filelist = new ArrayList<String>();
  Map<String,Long> formatFileMap = new HashMap<String,Long>();
   File  dir = new File(strpath);//通过路径来创建一个file实例
   File[] files = dir.listFiles();//返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件
  // System.out.println(""+files.length);
   if (files==null)
    System.out.println("该作业ID下文件为空") ;  
   for (int i=0;i<files.length;i++){
    formatFileMap.put(files[i].toString(),files[i].length() );
   }
   request.setAttribute("fileMap", formatFileMap);  
  return mapping.findForward("zyFileList");
 }

前台作业选择页面

<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>


  <html:form action="/batchSoftapp.do?method=fileDownLoad"  method="post">
 <div id="box_all">
  <div id="box_left">
     <table style="width:800px;"  class="tableList" border="1" cellspacing="0" cellpadding="0" style="table-layout: fixed;"  align="center" >
      <tr style="background-color:#D7F2F4" align="center">
     <td  class="fixhead"  width="8%">选择</td>
     <td  class="fixhead" width="75%" >文件名</td>
     <td  class="fixhead" width="17%" >文件大小</td>
      </tr>
      <%
         Map map = (Map)request.getAttribute("fileMap");
       //System.out.println("map.size"+map.size());
       if(map!=null){   
        Iterator   keyValuePairs = map.keySet().iterator();
        while(keyValuePairs.hasNext())   { 
         String filepath = (String)keyValuePairs.next();
         String filename =filepath.substring(filepath.lastIndexOf(");
         //System.out.println();
         Long filelength=(Long)map.get(filepath); 
      %>
      <tr>
     <td><input name="filechecked" id="filechecked" type="checkbox" checked= "true"  align="center" value="<%=filename %>,<%=filepath %>"> </td>
     <td><%=filename %> </td>
     <td><%=filelength%>字节 </td>
      </tr>
      <% }
       }
      %>
     </table>
  </div>
  <div id="box_right" align="center"> 
   <input type="button" value="全选" title="选择下载的文件" onclick="SelectAll(this.form)">
   <input type="button" value="反选" title="反向选择下载的文件" onclick="TurnOver(this.form)" >
   <input type="button" value="下载" title="下载选中的文件" onclick="DownLodSelected(this.form)">
   <input type="button" value="返回" title="返回作业ID列表页面" onclick="window.history.back()"> 
  </div>
  <input type="hidden" name="filenames" id="filenames" >
  <input type="hidden" name="filepaths"  >
 </div>
   </html:form>
  </body>
  </html:html>
<script type="text/javascript">
 /**
  * 功能:复选框全选
  * 参数:form对象
  * 思路:
  * 作者:   */
 function SelectAll(oForm){
  for(var i=0;i<oForm.filechecked.length;i++){
   oForm.filechecked[i].checked=true;  
  }
 }
  /**
  * 功能:复选框反选
  * 参数:form对象
  * 思路:
  * 作者:   */
 function TurnOver(oForm){
  for(var i=0;i<oForm.filechecked.length;i++){  
   oForm.filechecked[i].checked=!oForm.filechecked[i].checked;     
  }
 }
 /**
  * 功能:下载文件列表实现
  * 参数:form对象
  * 思路:
  * 作者:   */
 function DownLodSelected(oForm){
  if(confirm("因需要在服务端动态打包,需要时间比较长,是否继续批量下载?"))
  {//debugger;
   var arrDownloadList = [];   
   for(var i=0;i<document.getElementsByName("filechecked").length;i++)
   {
    if(document.getElementsByName("filechecked")[i].checked==true)
    {
     if(arrDownloadList.length==0){
                        arrDownloadList[0] = document.getElementsByName("filechecked").value;
                    }
     arrDownloadList[arrDownloadList.length] = document.getElementsByName("filechecked")[i].value;    
    }
   }
   if(arrDownloadList.length>0){
   var temp=[];
   var filenames="";
   var filepaths="";
   for(var i=1;i<arrDownloadList.length;i++){
   //alert("=========="+arrDownloadList[i])
    temp = arrDownloadList[i].split(",")
    if(filenames==""&&filepaths==""){
     filenames=temp[0];
     filepaths=temp[1];
    }else{
     filenames=filenames+"|"+temp[0];
     filepaths=filepaths+"|"+temp[1];    
    }
   }
   //alert("filenames==="+filenames);
   //alert("filepaths==="+filepaths);
    downloadFile(filenames,filepaths);    
  }else{
   alert("还没有选中下载项");  
  } 
  }

 }
 /**
 *功能: 文件下载
 *思路:
 *參數說明:复选框选中的要下载的文件名拼接,以及文件路径拼接
    *返回值  :
    *作者:    */
 function  downloadFile(filenames,filepaths){
    
  //location.href=encodeURI(encodeURI("/batchSoftapp.do?method=fileDownLoad&filenames="+filenames+"&filepaths="+filepaths));
  document.forms[0].filenames.value=filenames;
  document.forms[0].filepaths.value=filepaths;
  document.forms[0].submit();   
 }
</script> 

后台Action 部分关键部分

   String   filenames;
  String   filepaths;
  String[] filenameArray = null;
  String[] filepathArray = null;
  String   filename;
  String   filepath;
  SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
  filenames=request.getParameter("filenames");
  filepaths=request.getParameter("filepaths");
  System.out.println("filenames==================="+filenames);
  System.out.println("filepaths==================="+filepaths);
  filenameArray = filenames.split("传入要进行打包的所有文件
  filepathArray = filepaths.split("传入要进行打包的所有文件路径
  //filename="批量打包下载.zip";
  filename=format.format(new Date())+".zip";
  //String requestip =ServletActionContext.getRequest().getLocalAddr();
  System.out.println("*******************"+this.getServlet().getServletContext().getRealPath("/uploadfile/temp"));
  //filepath = "c://批量打包下载.zip";  //产生的压缩文件路径和名字
  filepath = this.getServlet().getServletContext().getRealPath("/uploadfile/temp")+";
  File tempfile = null;
  if(filenameArray!= null&&filepathArray!= null&&filenameArray.length>0 && filenameArray.length==filepathArray.length  ){
   try{
    File f=new File(filepath);
     f.createNewFile();
     ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
     out.putNextEntry(new ZipEntry("/"));
     for(int i=0;i<filepathArray.length;i++){
      //FileInputStream In = new FileInputStream(this.getServlet().getServletContext().getRealPath(filepathArray[i]));
     // System.out.println("路径"+this.getServlet().getServletContext().getRealPath(filepathArray[i]));
      FileInputStream In = new FileInputStream(filepathArray[i]);
      out.putNextEntry(new ZipEntry(filenameArray[i])); //开始写入新的 ZIP 文件条目并将流定位到条目数据的开始处    
      int b;
      while((b = In.read()) != -1) {
       out.write(b);
      }
      In.close();
     }    
     out.flush();
     out.close();
     tempfile = new File(filepath);
    String downFileNm=tempfile.getName();//取得要打包后要下载的文件的文件名(文件打包后的压缩文件)
    System.out.println("downFileNm===="+downFileNm);
    System.out.println("downFileNm.length===="+tempfile.length());
    //以流的形式下载文件
    InputStream fis = new BufferedInputStream(new FileInputStream(filepath));//获得目标下载文件输入流
    byte[] buffer = new byte[fis.available()];
    fis.read(buffer);
    fis.close();
    response.reset();//清空response
    // 设置response的Header
    //response.addHeader("Content-Disposition", "attachment;filename=" + new String(downFileNm.getBytes()));
    //是下载的那个文件另存为的时候的名字
    response.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(downFileNm,"UTF-8"));
    response.addHeader("Content-Length", "" + tempfile.length());
    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
    response.setContentType("application/octet-stream");//设置响应的MIME类型
    toClient.write(buffer);//你写的是buffer,也就是fis,也就是filepath这里对应的zip文件。这个是uuid.zip的话,上面的filename可以是abcd.zip
    toClient.flush();
    toClient.close();
   
   }catch(IOException e) {
    System.out.println("抛出异常:"+e.getMessage()+"   "+"压缩文件出错!!");

   }finally{
    if(tempfile.exists())
    {
    
     tempfile.delete();
     if(tempfile.exists())
     {
      System.out.println("---------删除临时文件失败-----------");

     }else
     {
      System.out.println("------删除打包产生的临时文件------");
     }
    }
   
   }
  
  }
  else{
   System.out.println("请求下载文件的路径或者文件名存在问题");
  }
 
  //return null ;

最后要说的有这么几点一个是参数中含有汉字的问题,tomcat中相关文件没有配置的话,解决后台乱码有这么两种方式,get方式发送时,前台jsp页面两次encodeURI(encodeURI("url跳转地址串"))后台再解码即可。再有就是post方式发送,将要传递的参数放置在input hidden的标签中,后台直接request.getParameter("参数名")也可,强烈推荐后面的处理方式。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/sdut_akaliusi202/archive/2010/02/04/5289066.aspx

原创粉丝点击