---
title: "struts2之单个文件上传"
author: "wcxt2012"
date: "2013-04-21T17:49:35Z"
tags: []
categories: ["企业架构"]
slug: "struts2"
draft: false
lastmod: "2013-04-21T17:50:28Z"
id: 1851045
url: "https://wcxt2012.iteye.com/blog/1851045"
---

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

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

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

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

开发步骤如下：

1、新建一个web工程，导入struts2上传文件所需jar，如下图

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

目录结构

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

            

2、新建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 {  
String realpath = ServletActionContext.getServletContext().getRealPath("/images");  
//D:\\apache-tomcat-6.0.18\\webapps\\struts2\_upload\\images  
System.out.println("realpath: "+realpath);  
if (image !=null) {  
File savefile =new File(new File(realpath), imageFileName);  
if (!savefile.getParentFile().exists())  
savefile.getParentFile().mkdirs();  
FileUtils.copyFile(image, savefile);  
ActionContext.getContext().put("message", "文件上传成功");  
}  
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;  
}

}

[![复制代码](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.io.IOException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

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

// 封装上传文件域的属性  
private File image;  
// 封装上传文件类型的属性  
private String imageContentType;  
// 封装上传文件名的属性  
private String imageFileName;  
// 接受依赖注入的属性  
private String savePath;

@Override  
public String execute() {  
FileOutputStream fos =null;  
FileInputStream fis =null;  
try {  
// 建立文件输出流  
System.out.println(getSavePath());  
fos =new FileOutputStream(getSavePath() +"\\\\"+ getImageFileName());  
// 建立文件上传流  
fis =new FileInputStream(getImage());  
byte\[] buffer =newbyte\[1024];  
int len =0;  
while ((len = fis.read(buffer)) &gt;0) {  
fos.write(buffer, 0, len);  
}  
} catch (Exception e) {  
System.out.println("文件上传失败");  
e.printStackTrace();  
} finally {  
close(fos, fis);  
}  
return SUCCESS;  
}

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

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

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;  
}

privatevoid close(FileOutputStream fos, FileInputStream fis) {  
if (fis !=null) {  
try {  
fis.close();  
} catch (IOException e) {  
System.out.println("FileInputStream关闭失败");  
e.printStackTrace();  
}  
}  
if (fos !=null) {  
try {  
fos.close();  
} catch (IOException e) {  
System.out.println("FileOutputStream关闭失败");  
e.printStackTrace();  
}  
}  
}

}

[![复制代码](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;!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) --&gt;  
&lt;constant name="struts.multipart.maxSize" value="10701096"/&gt;  
&lt;!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir --&gt;  
&lt;constant name="struts.multipart.saveDir " value="d:/tmp"/&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="upload2"extends="struts-default"&gt;  
&lt;action name="upload2"class="com.ljq.action.UploadAction2" method="execute"&gt;  
&lt;!-- 动态设置savePath的属性值 --&gt;  
&lt;param name="savePath"&gt;/images&lt;/param&gt;  
&lt;result name="success"&gt;/WEB-INF/page/message.jsp&lt;/result&gt;  
&lt;result name="input"&gt;/upload/upload.jsp&lt;/result&gt;  
&lt;interceptor-ref name="fileUpload"&gt;  
&lt;!-- 文件过滤 --&gt;  
&lt;param name="allowedTypes"&gt;image/bmp,image/png,image/gif,image/jpeg&lt;/param&gt;  
&lt;!-- 文件大小, 以字节为单位 --&gt;  
&lt;param name="maximumSize"&gt;1025956&lt;/param&gt;  
&lt;/interceptor-ref&gt;  
&lt;!-- 默认拦截器必须放在fileUpload之后，否则无效 --&gt;  
&lt;interceptor-ref name="defaultStack"/&gt;  
&lt;/action&gt;  
&lt;/package&gt;  
&lt;/struts&gt;

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

           

上传表单页面

[![复制代码](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;文件上传&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}/upload2/upload2.do--&gt;  
&lt;form action="${pageContext.request.contextPath}/upload2/upload2.do"  
enctype="multipart/form-data" method="post"&gt;  
文件:&lt;input type="file" name="image"&gt;  
&lt;input type="submit" value="上传"/&gt;  
&lt;/form&gt;  
&lt;br/&gt;  
&lt;s:fielderror /&gt;  
&lt;/body&gt;  
&lt;/html&gt;

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

           

显示结果页面

[![复制代码](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;上传成功&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;br/&gt;  
&lt;!-- ${pageContext.request.contextPath} tomcat部署路径，  
如：D:\\apache-tomcat-6.0.18\\webapps\\struts2\_upload\\ --&gt;  
&lt;img src="${pageContext.request.contextPath}/&lt;s:property value="'images/'+imageFileName"/&gt;"&gt;  
&lt;s:debug&gt;&lt;/s:debug&gt;  
&lt;/body&gt;  
&lt;/html&gt;

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