struts2多文件上传

来源:互联网 发布:淘宝客服简历表 编辑:程序博客网 时间:2024/05/17 04:43

转:http://hi.baidu.com/gingerlic/blog/item/a6e3e6d5e7382cc351da4b12.html

struts2 MVC作为一个新框架,功能强大,比之以前的版本1.x 强过不少。
无论是学习还是开发推荐 struts 2, 而且与spring ,Hibernate更易集成,可自定制需要的功能模块,还可以方便与ext 等js框架结合做ajax 开发。开发效率不错。

不多说,看一个多文件上传样例:

环境:JDK 1.6, TOMCAT 6.0, IDE:eclipse jee

主要的lib包:struts2-core- 2.0.11.1.jar,xwork-2.0.4.jar,freemarker.jar,ognl-2.6.11.jar,       pull-parser-2.1.10.jar,commons-fileupload.jar 必须的包。

代码:

package org;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.io.*;

public class UploadAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private File[] uploadFile;
private String[] contentType;
private String[] uploadFilename;

private String[] caption;

public String[] getCaption() {
   return caption;
}

public void setCaption(String[] caption) {
   this.caption = caption;
}

public String[] getContentType() {
   return contentType;
}

public void setUploadFileContentType(String[] contentType) {
   this.contentType = contentType;      // notice:here is the key!! 不要改变命名规范
}

public File[] getUploadFile() {
   return uploadFile;
}

public void setUploadFile(File[] uploadFile) {
   this.uploadFile = uploadFile;
}

public String[] getUploadFilename() {
   return uploadFilename;
}

public void setUploadFileFileName(String[] uploadFilename) {
   this.uploadFilename = uploadFilename;       // notice:here is the key!! 命名约定
}

private static void copy(File src, File dst) {
   try {
    InputStream in = null;
    OutputStream out = null;
    try {
     in = new BufferedInputStream(new FileInputStream(src));
     out = new BufferedOutputStream(new FileOutputStream(dst));
     byte[] buffer = new byte[16 * 1024];
     while (in.read(buffer) > 0) {
      out.write(buffer);
     }
    } finally {
     if (null != in) {
      in.close();
     }
     if (null != out) {
      out.close();
     }
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
}

public String execute() {
   for (int i = 0; i < this.getUploadFile().length; i++) {
    File imageFile = new File(ServletActionContext.getServletContext()
      .getRealPath("/")
      + "file/" + uploadFilename[i]);
    copy(this.getUploadFile()[i], imageFile);
   }
   return SUCCESS;
}

}

classes/目录下,struts.xml 文件配置:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "
http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <!-- developer mode convenient for Debug -->
    <constant name="struts.devMode" value="true" />
    <constant name="struts.i18n.encoding" value="GBK" />
    <package name="uploadFile" extends="struts-default">

       <action name="myUpload"
          class="org.UploadAction">
         
<interceptor-ref
             name="fileUpload">

             <param
                name="allowedTypes">
                image/bmp,image/png,image/gif,image/pjpeg,image/jpg,image/JPG,image/jpeg
             </param>
             <param
                name="maximumSize">
                1024000
             </param>
          </interceptor-ref>
          <interceptor-ref
             name="defaultStack" />
          <result name="input">
             /upload.jsp
          </result>
          <result name="success">
             /showUpload.jsp
          </result>
       </action>
    </package>
</struts>

web.xml配置:

<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"
http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
<web-app>
    <display-name>struts2上传文件示例</display-name>
    <filter>
       <filter-name>struts-cleanup</filter-name>
       <filter-class>
          org.apache.struts2.dispatcher.ActionContextCleanUp
       </filter-class>
    </filter>

    <filter>
       <filter-name>struts2</filter-name>
       <filter-class>
          org.apache.struts2.dispatcher.FilterDispatcher
       </filter-class>
    </filter>

 

    <!-- 注意顺序 -->
    <filter-mapping>
       <filter-name>struts-cleanup</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>


    <filter-mapping>
       <filter-name>struts2</filter-name>
       <url-pattern>/*</url-pattern>
    </filter-mapping>


    <welcome-file-list>
       <welcome-file>upload.jsp</welcome-file>
    </welcome-file-list>
</web-app>

上传页面(ognl 表达式):upload.jsp

<%@ page language="java" contentType="text/html;charset=gb2312"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<title>upload file</title>
<script type="text/javascript">  
    function addMore() {
        var td = document.getElementById("more");
        var div = document.createElement("div");
        var ss = document.createElement("span");
        var input = document.createElement("input");
        var span = document.createElement("span");
        var text = document.createElement("input");
        var button = document.createElement("input");
        div.style.marginTop = "4";
        ss.innerHTML = "选择文件:";
        input.type = "file";
        input.name = "uploadFile";
        span.innerHTML = "文件资源描述:";
        text.type = "text";
        text.size = 35;
        text.name = "caption";
        button.type = "button";
        button.value = "移 除";
        button.onclick = function() {
            td.removeChild(div);
            div = null;
            fileInputNumber--;
        }
        div.appendChild(ss);
        div.appendChild(input);
        div.appendChild(span);
        div.appendChild(text);
        div.appendChild(button);
        td.appendChild(div);
        fileInputNumber++;
    }
</script>
</head>

<body>
<s:fielderror />
<s:form method="post" name="uploadForm" action="myUpload"
        enctype="multipart/form-data" onsubmit="return check();"
        theme="simple">
        <tr>
            <td id="more">选择文件:<input type="file" name="uploadFile" />文件资源描述:<input
                type="text" name="caption" size="35" /><input type="button"
                value="添 加" onclick="addMore()" /></td>
        </tr>

        <tr>
            <td align="center"><s:submit value="上传" /> <s:reset value="重置" /></td>
        </tr>
    </s:form>
</body>
</html>

显示页面:showUpload.jsp

<%@ page language="java" contentType="text/html;charset=GBK"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
   <title>查看上传文件</title>
</head>
<body><center>
    <table border="1">
    <s:iterator value="uploadFilename" status="stat">
     <tr>
      <td>
       <s:property value="%{uploadFilename[#stat.index]}" />
       <br />
      </td>
     </tr>
     <tr>
      <td>
       <s:property value="%{caption[#stat.index]}" />
      </td>
     </tr>
     </s:iterator>
    </table>
   </center></body>
</html>

 

==================================================================

 

struts2中提供了对文件上传的支持,主要是通过File Upload Interceptor来实现的。这个拦截器有两个参数可以设置:maximumSize 和allowedTypes ,其中,maximumSize是允许上传的文件的最大容量,allowedTypes是允许的mimeType类型。

错误提示信息可以在i18n资源文件中指定,有以下三个key:

(1)struts.messages.error.uploading,文件上传出错时的提示信息

(2)struts.messages.error.file.too.large ,文件容量超出限制时的提示信息

(3)struts.messages.error.content.type.not.allowed ,文件mimeType类型不正确时的提示信息

1.如:在globleMessages_zh_CN.properties中,加入以下key-value:

struts.messages.error.uploading=上传文件失败
struts.messages.error.file.too.large=上传的文件太大
struts.messages.error.content.type.not.allowed=上传文件格式不正确

2.在action-mapping配置中:

xml 代码
  1. <interceptor-ref name="fileUpload">  
  2.                  <param name="allowedTypes">  
  3.                       image/png,image/gif,image/jpeg   
  4.                  param>  
  5.                  <!-- 文件最大不能size:以byte为单位 -->  
  6.                  <param name="maximumSize ">  
  7.                       102400   
  8.                  param>  
  9.             interceptor-ref>  

3.在JSP页面中:

(1)form表单中指定enctype="multipart/form-data":

xml 代码
  1. <s:form  name="certificate_form" onsubmit="return check()" enctype="multipart/form-data">  

 

xml 代码
  1. <s:file name="upload"><s:fielderror><s:param>uploads:param>s:fielderror>  

4.在Action中定义以下三个属性:

java 代码
  1. private File upload;   
  2. private String uploadFileName;     
  3. private String uploadContentType;  

并生成相应的setter,getter方法。指定上传的文件名为upload

5.struts.properties:

struts.multipart.saveDir=D:/strutsTemp
#struts.multipart.parser
#struts.multipart.maxSize

struts.multipart.parser默认为Commons FileUpload。是处理MultipartRequest的parse implementation。在File upload时使用。

struts.multipart.maxSize默认为约2M。

6.多文件上传:

在JSP页面中加入多个同名的file input,如:

 

 

 

然后在action中,把upload定义为数组或者List,相应的FileName和ContentType业为数组或List。

 

测试后,发现在添加一行时,td.appendChild(div)不可用,解决:可以在<td/>中添加一个<div id="filesID"></div>,然后把td.appendChild(div)方法替换为 document.getElementById('filesID').appendChild(div);即可。