---
title: "在Struts 2中实现文件上传"
author: "Allen.CD.China"
date: "2007-10-03T16:33:22Z"
tags: []
categories: ["企业架构"]
slug: "struts-2"
draft: false
lastmod: "2007-10-03T16:33:22Z"
id: 128967
url: "https://allenj2ee.iteye.com/blog/128967"
---

## 实现原理

Struts 2是通过Commons FileUpload文件上传。Commons FileUpload通过将HTTP的数据保存到临时文件夹，然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。

## 具体实现

前段时间Apache发布了Struts 2.0.6 GA，所以本文的实现是以该版本的Struts作为框架的。以下是例子所依赖类包的列表：

   
清单1 依赖类包的列表

首先，创建文件上传页面FileUpload.jsp，内容如下：

&lt;% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %&gt;  
&lt;% @ taglib prefix = " s " uri = " /struts-tags " %&gt;

&lt;! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" &gt;  
&lt; html xmlns ="http://www.w3.org/1999/xhtml" &gt;  
&lt; head &gt;  
    &lt; title &gt; Struts 2 File Upload &lt;/ title &gt;  
&lt;/ head &gt;  
&lt; body &gt;  
    &lt; s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" &gt;  
        &lt; s:file name ="myFile" label ="Image File" /&gt;  
        &lt; s:textfield name ="caption" label ="Caption" /&gt;          
        &lt; s:submit /&gt;  
    &lt;/ s:form &gt;  
&lt;/ body &gt;  
&lt;/ html &gt;

清单2 FileUpload.jsp

在FileUpload.jsp中，先将表单的提交方式设为POST，然后将enctype设为multipart/form-data，这并没有什么特别之处。接下来，&lt;s:file/&gt;标志将文件上传控件绑定到Action的myFile属性。

其次是FileUploadAction.java代码：

 package tutorial;

 import java.io.BufferedInputStream;  
 import java.io.BufferedOutputStream;  
 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.io.InputStream;  
 import java.io.OutputStream;  
 import java.util.Date;

 import org.apache.struts2.ServletActionContext;

 import com.opensymphony.xwork2.ActionSupport;

 public class FileUploadAction extends ActionSupport  {  
     private static final long serialVersionUID = 572146812454l ;  
     private static final int BUFFER\_SIZE = 16 * 1024 ;  
      
     private File myFile;  
     private String contentType;  
     private String fileName;  
     private String imageFileName;  
     private String caption;  
      
     public void setMyFileContentType(String contentType)  {  
         this .contentType = contentType;  
    }  
      
     public void setMyFileFileName(String fileName)  {  
         this .fileName = fileName;  
    }  
          
     public void setMyFile(File myFile)  {  
         this .myFile = myFile;  
    }  
      
     public String getImageFileName()  {  
         return imageFileName;  
    }  
      
     public String getCaption()  {  
         return caption;  
    }

      public void setCaption(String caption)  {  
         this .caption = caption;  
    }  
      
     private static void copy(File src, File dst)  {  
         try  {  
            InputStream in = null ;  
            OutputStream out = null ;  
             try  {                  
                in = new BufferedInputStream( new FileInputStream(src), BUFFER\_SIZE);  
                out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER\_SIZE);  
                 byte \[] buffer = new byte \[BUFFER\_SIZE];  
                 while (in.read(buffer) &gt; 0 )  {  
                    out.write(buffer);  
                }  
             } finally  {  
                 if ( null != in)  {  
                    in.close();  
                }  
                  if ( null != out)  {  
                    out.close();  
                }  
            }  
         } catch (Exception e)  {  
            e.printStackTrace();  
        }  
    }  
      
     private static String getExtention(String fileName)  {  
         int pos = fileName.lastIndexOf( " . " );  
         return fileName.substring(pos);  
    }

    @Override  
     public String execute()      {          
        imageFileName = new Date().getTime() + getExtention(fileName);  
        File imageFile = new File(ServletActionContext.getServletContext().getRealPath( " /UploadImages " ) + " / " + imageFileName);  
        copy(myFile, imageFile);  
         return SUCCESS;  
    }  
      
}

清单3 tutorial/FileUploadAction.java

在FileUploadAction中我分别写了setMyFileContentType、setMyFileFileName、setMyFile和setCaption四个Setter方法，后两者很容易明白，分别对应FileUpload.jsp中的&lt;s:file/&gt;和&lt;s:textfield/&gt;标志。但是前两者并没有显式地与任何的页面标志绑定，那么它们的值又是从何而来的呢？其实，&lt;s:file/&gt;标志不仅仅是绑定到myFile，还有myFileContentType（上传文件的MIME类型）和myFileFileName（上传文件的文件名，该文件名不包括文件的路径）。因此，&lt;s:file name="xxx" /&gt;对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。

FileUploadAction作用是将浏览器上传的文件拷贝到WEB应用程序的UploadImages文件夹下，新文件的名称是由系统时间与上传文件的后缀组成，该名称将被赋给imageFileName属性，以便上传成功的跳转页面使用。

下面我们就来看看上传成功的页面：

&lt;% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %&gt;  
&lt;% @ taglib prefix = " s " uri = " /struts-tags " %&gt;

&lt;! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" &gt;  
&lt; html xmlns ="http://www.w3.org/1999/xhtml" &gt;  
&lt; head &gt;  
    &lt; title &gt; Struts 2 File Upload &lt;/ title &gt;  
&lt;/ head &gt;  
&lt; body &gt;  
    &lt; div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" &gt;  
        &lt; img src ='UploadImages/&lt;s:property value ="imageFileName" /&gt; ' /&gt;  
        &lt; br /&gt;  
        &lt; s:property value ="caption" /&gt;  
    &lt;/ div &gt;  
&lt;/ body &gt;  
&lt;/ html &gt;

清单4 ShowUpload.jsp

ShowUpload.jsp获得imageFileName，将其UploadImages组成URL，从而将上传的图像显示出来。

然后是Action的配置文件：

&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; package name ="fileUploadDemo" extends ="struts-default" &gt;  
        &lt; action name ="fileUpload" class ="tutorial.FileUploadAction" &gt;  
            &lt; interceptor-ref name ="fileUploadStack" /&gt;  
            &lt; result name ="success" &gt; /ShowUpload.jsp &lt;/ result &gt;  
        &lt;/ action &gt;  
    &lt;/ package &gt;  
&lt;/ struts &gt;

清单5 struts.xml

fileUpload Action显式地应用fileUploadStack的拦截器。

最后是web.xml配置文件：

&lt;? xml version="1.0" encoding="UTF-8" ?&gt;  
&lt; web-app id ="WebApp\_9" version ="2.4"  
    xmlns ="http://java.sun.com/xml/ns/j2ee"  
    xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation ="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app\_2\_4.xsd" &gt;

    &lt; display-name &gt; Struts 2 Fileupload &lt;/ display-name &gt;

    &lt; filter &gt;  
        &lt; filter-name &gt; struts-cleanup &lt;/ filter-name &gt;  
        &lt; filter-class &gt;  
            org.apache.struts2.dispatcher.ActionContextCleanUp  
        &lt;/ filter-class &gt;  
    &lt;/ filter &gt;  
      
    &lt; filter &gt;  
        &lt; filter-name &gt; struts2 &lt;/ filter-name &gt;  
        &lt; filter-class &gt;  
            org.apache.struts2.dispatcher.FilterDispatcher  
        &lt;/ filter-class &gt;  
    &lt;/ filter &gt;  
      
    &lt; filter-mapping &gt;  
        &lt; filter-name &gt; struts-cleanup &lt;/ filter-name &gt;  
        &lt; url-pattern &gt; /* &lt;/ url-pattern &gt;  
    &lt;/ filter-mapping &gt;

    &lt; filter-mapping &gt;  
        &lt; filter-name &gt; struts2 &lt;/ filter-name &gt;  
        &lt; url-pattern &gt; /* &lt;/ url-pattern &gt;  
    &lt;/ filter-mapping &gt;

    &lt; welcome-file-list &gt;  
        &lt; welcome-file &gt; index.html &lt;/ welcome-file &gt;  
    &lt;/ welcome-file-list &gt;

&lt;/ web-app &gt;

清单6 WEB-INF/web.xml

发布运行应用程序，在浏览器地址栏中键入：[http://localhost:8080/Struts2\_Fileupload/FileUpload.jsp](http://localhost:8080/Struts2_Fileupload/FileUpload.jsp)，出现图示页面：

清单7 FileUpload页面

选择图片文件，填写Caption并按下Submit按钮提交，出现图示页面：