我用的版本是Struts2.1.8
第一步:添加jar包commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
第二部:在index.jsp中添加如下代码:
<form action="upload.action" method="post" enctype="multipart/form-data">
上传文件:<input type="file" name="upload" /><br>
<input value="上传" type="submit" /> </from>
第三步:在struts.xml里配置如下:
<!--指定文件临时存储空间 -->
<constant name="struts.multipart.saveDir" value="/temp" />
<constant name="struts.i18n.encoding" value="UTF-8"/>
<action name="upload" class="action.UploadAction">
<!-- 动态设置Action的属性值 -->
<param name="savePath">/upload</param>
<!-- 配置Struts2默认的视图页面 -->
<result>/welcome.jsp</result>
</action>
第四步:新建一个action包并新建类UploadAction
private File upload;
private String uploadContentType;
private String uploadFileName;
private String savePath;
public void setSavePath(String value)
{
this.savePath = value;
}
private String getSavePath() throws Exception {
return ServletActionContext.getRequest().getRealPath(savePath);
}
public void setUpload(File upload)
{
this.upload = upload;
}
public File getUpload()
{
return (this.upload);
}
public void setUploadContentType(String uploadContentType)
{
this.uploadContentType = uploadContentType;
}
public String getUploadContentType()
{
return (this.uploadContentType);
}
public void setUploadFileName(String uploadFileName)
{
this.uploadFileName = uploadFileName;
}
public String getUploadFileName()
{
return (this.uploadFileName);
}
@Override
public String execute() throws Exception
{
FileOutputStream fos = new FileOutputStream(getSavePath()
+ "\\" + getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer , 0 , len);
}
return SUCCESS;
}
web.xm下新增如下代码:
<!-- 配置Struts2的CleanUp的Filter -->
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<!-- 定义Struts2的CleanUp Filter拦截的URL -->
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在项目下新建一个upload文件夹
完成!!!