---
title: "strtus2 批量下载 中文问题、压缩文件等 ------ 讨论struts2工作流程 "
author: "aben328"
date: "2009-11-23T16:34:23Z"
tags: ["DWR", "JSP", "JavaScript", "Struts", "工作"]
slug: "strtus2-struts2"
draft: false
lastmod: "2009-11-23T16:34:23Z"
id: 523738
url: "https://aben328.iteye.com/blog/523738"
---

[strtus2 批量下载 中文问题、压缩文件等 ------ 讨论struts2工作流程](http://www.blogjava.net/xcp/archive/2009/10/30/downloadList.html)

       最近因为一个项目,需要做统一的下载,并且要支持批量下载..其中涉及到的知识点有:get请求中文处理,下载动态设置下载名,批量下载,动态打包,流处理,删除临时文件,使用迅雷下载后台发出两次次下载请求,以及struts2工作流程与原理等..  
         
       下面是我自己做的一个实例,主要实现遍历一个文件夹生成下载列表,用户可以单一下载,也可选择相关文件批量下载.....做的其中发现有很多疑惑的地方,请高手们指出....谢谢  
        
      **一.实例区**  
      1.index.html  
      

&lt;%@ page language="java" pageEncoding="gbk"%&gt;  
&lt;%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%&gt;

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;  
&lt;html&gt;  
  &lt;head&gt;  
    &lt;base href="&lt;%=basePath%&gt;"&gt;  
      
    &lt;title&gt;My JSP 'index.jsp' starting page&lt;/title&gt;  
    &lt;meta http-equiv="pragma" content="no-cache"&gt;  
    &lt;meta http-equiv="cache-control" content="no-cache"&gt;  
    &lt;meta http-equiv="expires" content="0"&gt;      
    &lt;meta http-equiv="keywords" content="keyword1,keyword2,keyword3"&gt;  
    &lt;meta http-equiv="description" content="This is my page"&gt;  
    &lt;!--  
    &lt;link rel="stylesheet" type="text/css" href="styles.css"&gt;  
    --&gt;  
  &lt;/head&gt;  
    
  &lt;body&gt;  
           &lt;hr&gt;  
           &lt;h3&gt;欢迎光临下载区&lt;/h3&gt;  
           &lt;a href="downloadList.action"&gt;下载列表&lt;/a&gt;&lt;br/&gt;  
  &lt;/body&gt;  
&lt;/html&gt;

      2.配置struts.xml  
      

&lt;?xml version="1.0" encoding="UTF-8" ?&gt;  
&lt;!DOCTYPE struts PUBLIC  
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
    "http://struts.apache.org/dtds/struts-2.0.dtd"&gt;  
&lt;struts&gt;

    &lt;constant name="struts.custom.i18n.resources" value="message"&gt;&lt;/constant&gt;  
    &lt;constant name="struts.i18n.encoding" value="gbk"&gt;&lt;/constant&gt;  
    &lt;constant name="struts.multipart.saveDir" value="/tmp"&gt;&lt;/constant&gt;  
    &lt;constant name="struts.multipart.maxSize" value="209715200" /&gt;  
      
    &lt;package name="struts2" extends="struts-default"&gt;  
      
      
        &lt;action name="downloadList" class="cn.edu.cuit.disasterSystem.web.struts2.action.DownloadListAction"&gt;  
            &lt;result name="success"&gt;/downloadList.jsp&lt;/result&gt;  
            &lt;result name="error"&gt;/downloadListError.jsp&lt;/result&gt;          
        &lt;/action&gt;  
      
      
          
            &lt;action name="download" class="cn.edu.cuit.disasterSystem.web.struts2.action.DownloadAction"&gt;  
            &lt;result name="success" type="stream"&gt;  
                &lt;!-- contentType为二进制方式 --&gt;  
                &lt;param name="contentType"&gt;application/octet-stream;charset=ISO8859-1&lt;/param&gt;  
                &lt;!-- attachment属性强调是下载,就不会主动打开,比如图片 --&gt;  
                &lt;!-- 使用经过转码的文件名作为下载文件名，downloadFileName属性对应action类中的方法 getDownloadFileName() --&gt;  
                &lt;param name="contentDisposition"&gt;  
                    attachment;filename=${filename}  
                &lt;/param&gt;  
                &lt;param name="inputName"&gt;downloadFile&lt;/param&gt;  
                &lt;param name="bufferSize"&gt;4096&lt;/param&gt;  
            &lt;/result&gt;  
            &lt;result name="input"&gt;/downloadList.jsp&lt;/result&gt;  
            &lt;result name="error"&gt;/downloadListError.jsp&lt;/result&gt;  
        &lt;/action&gt;  
    &lt;/package&gt;  
&lt;/struts&gt;

      3.产生下载列表的Action----DownloadListAction

package cn.edu.cuit.disasterSystem.web.struts2.action;

import java.io.File;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;  
import com.opensymphony.xwork2.ActionSupport;

/\**  
 * 显示所有down目录的文件,供下载所用  
 * @author  xcp  
 * @version  1.0  
 * Copyright (C), 2009 智能开发实验室 所有  
 * Program Name:灾情信息管理系统  
 * Date: 2009-10-24 上午11:16:41  
 \*/  
@SuppressWarnings("serial")  
public class DownloadListAction  extends ActionSupport{  
      
    private static ArrayList&lt;String&gt; filelist = new ArrayList&lt;String&gt;();  
      
      
    /\**  
     *    可以是前台一个页面传入,也可以是手动指定,其作用是指定下载文件的根目录  
     * @author  向才鹏  
     * 2009-10-24 下午12:02:47  
     \*/  
    private String downloadRootPath = "/upload";  
      
    public String getDownloadRootPath() {  
        return downloadRootPath;  
    }  
    public void setDownloadRootPath(String downloadRootPath) {  
        this.downloadRootPath = downloadRootPath;  
    }

    /\**  
     * 将指定文件路径下的文件全部遍历出来   
     * @author 向才鹏  
     * @param strPath 指来要遍历的文件  
     * 2009-10-24   下午12:04:48  
     \*/  
    public static void refreshFileList(String strPath)  
    {  
        File dir = new File(strPath);  
        File\[] files = dir.listFiles();

        if (files == null)  
            return;  
        for (int i = 0; i &lt; files.length; i++)  
        {  
            if (files\[i].isDirectory())  
            {  
                refreshFileList(files\[i].getAbsolutePath());  
            } else  
            {  
                String filePath =  files\[i].getPath();  
                filelist.add(filePath);  
            }  
        }  
    }

      
      
    /\**  
     * 格式化输出数据存入Map,形式文件名+文件服务端路径  
     * @author 向才鹏  
     * @param filelist 遍历出来的文件路径  
     * @param downloadRootPath 指明服务器下载的文件,便于从遍历出来的文件中取得服务端路径  
     * @return  
     * 2009-10-24   下午12:06:18  
     \*/  
    private static Map&lt;String,String&gt; formatFileMap(ArrayList&lt;String&gt; filelist,String downloadRootPath){  
        Map&lt;String,String&gt; formatFileMap = new HashMap&lt;String,String&gt;();  
        //得到服务下载的根路径,并将/换成\\\\,这样便于替换  
        String formatDownloadRootPath =  downloadRootPath.replaceAll("/", "\\\\\\\\");  
        for(String filePath : filelist){  
            //得到下载的相对路径  
            String  downloadPath = filePath.substring(filePath.indexOf(formatDownloadRootPath));  
            //将得到的相对路径的\\\\转换成/  
            String formatDownloadPath = downloadPath.replaceAll("\\\\\\\\", "/");  
            //得到文件名  
            String filename = formatDownloadPath.substring(formatDownloadPath.lastIndexOf("/")+1);  
          
            /\*try {  
                formatFileMap.put(filename, URLEncoder.encode(formatDownloadPath, "gbk"));  
            } catch (UnsupportedEncodingException e) {  
                formatFileMap.put(filename, formatDownloadPath);  
                e.printStackTrace();  
            }\*/  
              
            //这就不用考虑设置编码了，再后面统一使用javascript的encodeURI函数  
            formatFileMap.put(filename, formatDownloadPath);  
              
        }  
        return formatFileMap;  
    }  
      
      
    @SuppressWarnings("unchecked")  
    @Override  
    public String execute() throws Exception {  
          
        //指定下载目录  
        String upload = ServletActionContext.getServletContext().getRealPath(downloadRootPath);  
        //清理filelist  
        filelist.clear();  
        //遍历文件  
        refreshFileList(upload);  
          
        ActionContext context = ActionContext.getContext();  
        Map request = (Map) context.get("request");  
          
          
        if(filelist != null){  
            //格式化文件信息,包括文件名和地址  
            Map&lt;String,String&gt; formatFileMap = formatFileMap(filelist,downloadRootPath);  
            request.put("fileMap", formatFileMap);  
            return SUCCESS;  
        }  
        else{  
            request.put("errorMessage", "没有相关的下载文件");  
            return ERROR;  
        }  
              
    }  
      
      
}

      4.显示下载列表downloadList.jsp

&lt;%@ page language="java" contentType="text/html; charset=gbk"  
    pageEncoding="gbk"%&gt;

&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;  
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;  
&lt;script type="text/javascript"&gt;  
    function downloadFile1(filenames,filepaths){  
        location.href=encodeURI("download.action?filenames="+filenames+"&filepaths="+filepaths);  
    }  
    function SelectAll(oForm)  
    {  
        for(var i=0;i&lt;oForm.url.length;i++)  
        {  
            oForm.url\[i].checked=true;  
        }  
    }  
    function TurnOver(oForm)  
    {  
        for(var i=0;i&lt;oForm.url.length;i++)  
        {  
            oForm.url\[i].checked=!oForm.url\[i].checked;  
        }  
    }  
    function DownlodSelected(oForm){  
         if(confirm("因需要在服务端动态打包,需要时间比较长,是否继续批量下载?"))  
            {  
             var arrDownloadList = \[];  
            for(var i=0;i&lt;oForm.url.length;i++){  
                if(oForm.url\[i].checked==true){  
                    if(arrDownloadList.length==0){  
                        arrDownloadList\[0] = oForm.url.value;  
                    }  
                    arrDownloadList\[arrDownloadList.length] = oForm.url\[i].value;  
                }  
            }  
            if (arrDownloadList.length&gt;0){  
                var temp = \[];  
                var filenames="";  
                var filepaths="";  
                for(var i=1;i&lt;arrDownloadList.length;i++){  
                    temp = arrDownloadList\[i].split(",")  
                    if(filenames=="" && filepaths==""){  
                        filenames=temp\[0]  
                        filepaths=temp\[1]  
                    }else{      
                        filenames=filenames+"|"+temp\[0];  
                        filepaths=filepaths+"|"+temp\[1];  
                    }  
                }  
                downloadFile1(filenames,filepaths);  
            }else{  
                alert("还没有选中下载项");  
            }  
           }  
    }  
&lt;/script&gt;  
&lt;html&gt;  
    &lt;head&gt;  
        &lt;meta http-equiv="Content-Type" content="text/html; charset=GB18030"&gt;  
        &lt;title&gt;Insert title here&lt;/title&gt;  
        &lt;script type="text/javascript" src="dwr/engine.js"&gt;&lt;/script&gt;  
        &lt;script type="text/javascript" src="dwr/util.js"&gt;&lt;/script&gt;  
        &lt;script type="text/javascript" src="dwr/interface/downloaddwr.js"&gt;&lt;/script&gt;  
    &lt;/head&gt;  
    &lt;body&gt;  
        &lt;form name="myform" style="display: inline" onSubmit="return false"&gt;  
            &lt;table width="50%" align="center"&gt;  
                &lt;tr&gt;  
                    &lt;td colspan="2"&gt;  
                        &lt;h3&gt;  
                            以后是下载列表,点击进行下载  
                        &lt;/h3&gt;  
                    &lt;/td&gt;  
                &lt;/tr&gt;  
                &lt;tr&gt;  
                    &lt;td colspan="2"&gt;  
                        &lt;font color="red"&gt;&lt;s:fielderror&gt;&lt;/s:fielderror&gt; &lt;/font&gt;  
                    &lt;/td&gt;  
                &lt;/tr&gt;  
                &lt;s:iterator value="#request.fileMap" status="stuts"&gt;  
                    &lt;s:if test="#stuts.odd == true"&gt;  
                        &lt;tr style="background-color: #77D9F6"&gt;  
                            &lt;td&gt;  
                                &lt;input name="url" type="checkbox" id="url"  
                                    value="&lt;s:property value="key" /&gt;,&lt;s:property value="value" /&gt;"&gt;  
                            &lt;/td&gt;  
                            &lt;td&gt;  
                                &lt;s:property value="key" /&gt;  
                            &lt;/td&gt;  
                            &lt;td&gt;  
                                &lt;a href="#"  
                                    onclick="downloadFile1('&lt;s:property value="key" /&gt;','&lt;s:property value="value" /&gt;')"&gt;点击下载&lt;/a&gt;  
                            &lt;/td&gt;  
                        &lt;/tr&gt;  
                    &lt;/s:if&gt;  
                    &lt;s:else&gt;  
                        &lt;tr style="background-color: #D7F2F4"&gt;  
                            &lt;td&gt;  
                                &lt;input name="url" type="checkbox" id="url"  
                                    value="&lt;s:property value="key" /&gt;,&lt;s:property value="value" /&gt;"&gt;  
                            &lt;