1.导入struts的包
commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-io-1.1.jar
2.建立jsp页面
2.1 先将表单的提交方式设为POST,然后将enctype设为multipart/form-data
2.2 <input type="file" name="paperFile" size="30" /> 例如在页面上有个name定义为paperFile的文件
3.在Action里写以下代码
3.1 定义相关属性
private static final int BUFFER_SIZE = 16 * 1024 ;
private File paperFile; //对应jsp页面上的name
private String contentType; //上传文件的MIME类型,必参
private String fileName; //文件名
3.2 生成相应的set方法
/**
*必须方法
* 把页面上的文件类型传到action,
* 方法写法 set{jsp页面定义的file的name,首字母大写}ContentType(String contentType)
* {this .contentType = contentType;}
* @param contentType
*/
public void setPaperFileContentType(String contentType) {
this.contentType = contentType; //这里的this.contentType 就是上面定义的属性
}
/**
* 必须方法
* 把页面上的文件名传到action,
* 方法写法 set{jsp页面定义的file的name,首字母大写}FileName(String fileName)
* {this .fileName = fileName;}
* @param fileName
*/
public void setPaperFileFileName(String fileName) {
this.fileName = fileName; //这里的this.fileName 就是上面定义的属性
}
/**
* 必须方法,
* 把文件传到action
* @param paperFile
*/
public void setPaperFile(File paperFile) {
this.paperFile = paperFile;
}
4. 要struts 配置中加入以下内容
<action name="fileUpload" class="com.doone.servant.exam.action.PaperAction" method="UploadPaper">
<interceptor-ref name ="fileUploadStack" /> <!--这是必须加的,因为Struts使用fileUpload拦截器将文件绑定到Action的实例-->
<result>/exam/exam_manage/paper_list.jsp</result>
</action>
5. 在工程的web.xml上配置
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
6. 上面的步骤只是把文件上传到一个临时文件夹下.下面我们要做的是从临时文件夹下把这个文件拷贝到自己定义的文件夹下
使用 工具里面的 FileUtils.copyFile(原文件,新的文件夹); 方法来实现.