使用struts2上传文件
1.首先你要配置好struts2项目的基本结构,引入struts2的lib包
2.配置web.xml,加入如下内容
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.配置struts2.xml文件,在default package下加入如下内容
<package name="default" namespace="/" extends="struts-default">
<action name="upload" class="com.it.action.fileuploadAction">
<result>/jsp/upload.jsp</result>
<result name="input">/jsp/error.jsp</result>
<!-- 配置拦截器 -->
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/bmp,image/x-png,image/jpeg</param>//上传文件的格式
<param name="maximumSize">2M</param>//上传文件的大小
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
</package>
4.在上传页面的form表单上加入enctype="multipart/form-data" method="post"
5.写Action
package
com.example;
import
java.io.File;
import
com.opensymphony.xwork2.ActionSupport;
public
class
UploadAction
extends
ActionSupport {
private
File file;
private
String contentType;
private
String filename;
public
void
setUpload(File file) {
this
.file = file;
}
public
void
setUploadContentType(String contentType) {
this
.contentType = contentType;
}
public
void
setUploadFileName(String filename) {
this
.filename = filename;
}
public
String execute() {
//...
return
SUCCESS;
}
}
属性必须包含以上3个,且set方法必须符合如下命名格式
|