---
title: "struts2之多个文件上传"
author: "wcxt2012"
date: "2013-04-21T17:52:00Z"
tags: []
categories: ["企业架构"]
slug: "struts2"
draft: false
lastmod: "2013-04-21T17:52:00Z"
id: 1851047
url: "https://wcxt2012.iteye.com/blog/1851047"
---

# [struts2之多个文件上传](http://www.cnblogs.com/linjiqin/archive/2011/03/21/1990688.html)

通过3种方式模拟多个文件上传，效果如下所示

![](http://pic002.cnblogs.com/images/2011/270324/2011032120584292.png)

         

目录结构

 ![](http://pic002.cnblogs.com/images/2011/270324/2011032120592080.png)

新建Action

第一种方式

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

package com.ljq.action;

import java.io.File;

import org.apache.commons.io.FileUtils;  
import org.apache.struts2.ServletActionContext;

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

@SuppressWarnings("serial")  
publicclass UploadAction extends ActionSupport{

private File\[] image; //上传的文件  
private String\[] imageFileName; //文件名称  
private String\[] imageContentType; //文件类型

public String execute() throws Exception {  
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");  
String realpath = ServletActionContext.getServletContext().getRealPath("/images");  
System.out.println(realpath);  
if (image !=null) {  
File savedir=new File(realpath);  
if(!savedir.getParentFile().exists())  
savedir.getParentFile().mkdirs();  
for(int i=0;i&lt;image.length;i++){  
File savefile =new File(savedir, imageFileName\[i]);  
FileUtils.copyFile(image\[i], savefile);  
}  
ActionContext.getContext().put("message", "文件上传成功");  
}  
return"success";  
}

public File\[] getImage() {  
return image;  
}

publicvoid setImage(File\[] image) {  
this.image = image;  
}

public String\[] getImageContentType() {  
return imageContentType;  
}

publicvoid setImageContentType(String\[] imageContentType) {  
this.imageContentType = imageContentType;  
}

public String\[] getImageFileName() {  
return imageFileName;  
}

publicvoid setImageFileName(String\[] imageFileName) {  
this.imageFileName = imageFileName;  
}

}

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

                   

第二种方式

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

package com.ljq.action;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;  
/\**  
\* 使用数组上传多个文件  
\*  
\* @author ljq  
\*  
\*/  
@SuppressWarnings("serial")  
publicclass UploadAction2 extends ActionSupport{  
private File\[] image; //上传的文件  
private String\[] imageFileName; //文件名称  
private String\[] imageContentType; //文件类型  
private String savePath;

@Override  
public String execute() throws Exception {  
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");  
//取得需要上传的文件数组  
File\[] files = getImage();  
if (files !=null&& files.length &gt;0) {  
for (int i =0; i &lt; files.length; i++) {  
//建立上传文件的输出流, getImageFileName()\[i]  
System.out.println(getSavePath() +"\\\\"+ getImageFileName()\[i]);  
FileOutputStream fos =new FileOutputStream(getSavePath() +"\\\\"+ getImageFileName()\[i]);  
//建立上传文件的输入流  
FileInputStream fis =new FileInputStream(files\[i]);  
byte\[] buffer =newbyte\[1024];  
int len =0;  
while ((len=fis.read(buffer))&gt;0) {  
fos.write(buffer, 0, len);  
}  
fos.close();  
fis.close();  
}  
}  
return SUCCESS;  
}

public File\[] getImage() {  
return image;  
}

publicvoid setImage(File\[] image) {  
this.image = image;  
}

public String\[] getImageFileName() {  
return imageFileName;  
}

publicvoid setImageFileName(String\[] imageFileName) {  
this.imageFileName = imageFileName;  
}

public String\[] getImageContentType() {  
return imageContentType;  
}

publicvoid setImageContentType(String\[] imageContentType) {  
this.imageContentType = imageContentType;  
}

/\**  
\* 返回上传文件保存的位置  
\*  
\* @return  
\* @throws Exception  
\*/  
public String getSavePath() throws Exception {  
return ServletActionContext.getServletContext().getRealPath(savePath);  
}

publicvoid setSavePath(String savePath) {  
this.savePath = savePath;  
}

}

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

            

第三种方式

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

package com.ljq.action;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/\**  
\* 使用List上传多个文件  
\*  
\* @author ljq  
\*  
\*/  
@SuppressWarnings("serial")  
publicclass UploadAction3 extends ActionSupport {  
private List&lt;File&gt; image; // 上传的文件  
private List&lt;String&gt; imageFileName; // 文件名称  
private List&lt;String&gt; imageContentType; // 文件类型  
private String savePath;

@Override  
public String execute() throws Exception {  
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");  
// 取得需要上传的文件数组  
List&lt;File&gt; files = getImage();  
if (files !=null&& files.size() &gt;0) {  
for (int i =0; i &lt; files.size(); i++) {  
FileOutputStream fos =new FileOutputStream(getSavePath() +"\\\\"+ getImageFileName().get(i));  
FileInputStream fis =new FileInputStream(files.get(i));  
byte\[] buffer =newbyte\[1024];  
int len =0;  
while ((len = fis.read(buffer)) &gt;0) {  
fos.write(buffer, 0, len);  
}  
fis.close();  
fos.close();  
}  
}  
return SUCCESS;  
}

public List&lt;File&gt; getImage() {  
return image;  
}

publicvoid setImage(List&lt;File&gt; image) {  
this.image = image;  
}

public List&lt;String&gt; getImageFileName() {  
return imageFileName;  
}

publicvoid setImageFileName(List&lt;String&gt; imageFileName) {  
this.imageFileName = imageFileName;  
}

public List&lt;String&gt; getImageContentType() {  
return imageContentType;  
}

publicvoid setImageContentType(List&lt;String&gt; imageContentType) {  
this.imageContentType = imageContentType;  
}

/\**  
\* 返回上传文件保存的位置  
\*  
\* @return  
\* @throws Exception  
\*/  
public String getSavePath() throws Exception {  
return ServletActionContext.getServletContext().getRealPath(savePath);  
}

publicvoid setSavePath(String savePath) {  
this.savePath = savePath;  
}

}

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

              

struts.xml配置文件

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

&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;!-- 该属性指定需要Struts2处理的请求后缀，该属性的默认值是action，即所有匹配\*.action的请求都由Struts2处理。  
如果用户需要指定多个请求后缀，则多个后缀之间以英文逗号（,）隔开。 --&gt;  
&lt;constant name="struts.action.extension" value="do"/&gt;  
&lt;!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 --&gt;  
&lt;constant name="struts.serve.static.browserCache" value="false"/&gt;  
&lt;!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 --&gt;  
&lt;constant name="struts.configuration.xml.reload" value="true"/&gt;  
&lt;!-- 开发模式下使用,这样可以打印出更详细的错误信息 --&gt;  
&lt;constant name="struts.devMode" value="true"/&gt;  
&lt;!-- 默认的视图主题 --&gt;  
&lt;constant name="struts.ui.theme" value="simple"/&gt;  
&lt;!--&lt;constant name="struts.objectFactory" value="spring"/&gt;--&gt;  
&lt;!--解决乱码 --&gt;  
&lt;constant name="struts.i18n.encoding" value="UTF-8"/&gt;  
&lt;constant name="struts.multipart.maxSize" value="10701096"/&gt;

&lt;package name="upload" namespace="/upload"extends="struts-default"&gt;  
&lt;action name="\*\_upload"class="com.ljq.action.UploadAction" method="{1}"&gt;  
&lt;result name="success"&gt;/WEB-INF/page/message.jsp&lt;/result&gt;  
&lt;/action&gt;  
&lt;/package&gt;  
&lt;package name="upload1" namespace="/upload1"extends="struts-default"&gt;  
&lt;action name="upload1"class="com.ljq.action.UploadAction2" method="execute"&gt;  
&lt;!-- 要创建/image文件夹，否则会报找不到文件 --&gt;  
&lt;param name="savePath"&gt;/image&lt;/param&gt;  
&lt;result name="success"&gt;/WEB-INF/page/message.jsp&lt;/result&gt;  
&lt;/action&gt;  
&lt;/package&gt;  
&lt;package name="upload2" namespace="/upload2"extends="struts-default"&gt;  
&lt;action name="upload2"class="com.ljq.action.UploadAction3" method="execute"&gt;  
&lt;!-- 要创建/image文件夹，否则会报找不到文件 --&gt;  
&lt;param name="savePath"&gt;/image&lt;/param&gt;  
&lt;result name="success"&gt;/WEB-INF/page/message.jsp&lt;/result&gt;  
&lt;/action&gt;  
&lt;/package&gt;  
&lt;/struts&gt;

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

           

上传表单页面upload.jsp

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

&lt;%@ page language="java"import="java.util.\*" pageEncoding="UTF-8"%&gt;

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;  
&lt;html&gt;  
&lt;head&gt;  
&lt;title&gt;文件上传&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;/head&gt;

&lt;body&gt;  
&lt;!-- ${pageContext.request.contextPath}/upload/execute\_upload.do--&gt;  
&lt;!-- ${pageContext.request.contextPath}/upload1/upload1.do--&gt;  
&lt;!-- ${pageContext.request.contextPath}/upload2/upload2.do--&gt;  
&lt;!----&gt;  
&lt;form action="${pageContext.request.contextPath}/upload2/upload2.do" enctype="multipart/form-data" method="post"&gt;  
文件1:&lt;input type="file" name="image"&gt;&lt;br/&gt;  
文件2:&lt;input type="file" name="image"&gt;&lt;br/&gt;  
文件3:&lt;input type="file" name="image"&gt;&lt;br/&gt;  
&lt;input type="submit" value="上传"/&gt;  
&lt;/form&gt;  
&lt;/body&gt;  
&lt;/html&gt;

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

显示页面message.jsp

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

&lt;%@ page language="java"import="java.util.\*" pageEncoding="UTF-8"%&gt;  
&lt;%@ taglib uri="/struts-tags" prefix="s"%&gt;  
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;  
&lt;html&gt;  
&lt;head&gt;

&lt;title&gt;My JSP 'message.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;/head&gt;

&lt;body&gt;  
上传成功  
&lt;br/&gt;  
&lt;s:debug&gt;&lt;/s:debug&gt;  
&lt;/body&gt;  
&lt;/html&gt;

 

文章转载路径：[http://www.cnblogs.com/linjiqin/archive/2011/03/21/1990688.html](http://www.cnblogs.com/linjiqin/archive/2011/03/21/1990688.html)