首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

struts2下传文件(commons-fileupload-1.2.1)

2012-10-08 
struts2上传文件(commons-fileupload-1.2.1)struts版本为struts-2.1.8.1?项目名为 struts2?从路径 struts-

struts2上传文件(commons-fileupload-1.2.1)

struts版本为struts-2.1.8.1

?

项目名为 struts2

?

从路径 struts-2.1.8.1\lib 下将 struts2-core-2.1.8.1.jar,xwork-core-2.1.6.jar,commons-fileupload-1.2.1.jar,commons-io-1.3.2.jar 复制到 WEB-INF/lib 目录下

?

配置struts.xml文件

?

?

?

创建第一个页面 fileupload.jsp (用于上传文件)

?

?

创建第二个页面 /page/message.jsp (用于显示返回信息)

?

?

创建处理文件上传的Action

?

package com.cool.fileupload;import java.io.File;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;public class FileUploadAction {private File image;private String imageFileName;public File getImage() {return image;}public void setImage(File image) {this.image = image;}public String getImageFileName() {return imageFileName;}public void setImageFileName(String imageFileName) {this.imageFileName = imageFileName;}public String execute() throws Exception{String realPath = ServletActionContext.getServletContext().getRealPath("/image");if(this.image!=null){File saveFile = new File(new File(realPath), this.imageFileName);if(!saveFile.getParentFile().exists())saveFile.getParentFile().mkdirs();FileUtils.copyFile(image, saveFile);}ActionContext.getContext().put("message","上传成功");return "success";}}访问路径为 http://localhost:8080/struts2/fileupload.jsp (struts2为项目名)选择文件,然后单击上传按钮,画面跳转到 /page/message.jsp,显示【上传成功】然后到发布路径下看文件是否真正上传 F:\Tomcat\webapps\struts2\image ( F:\Tomcat 为本机Tomcat路径 )测试成功。关于多文件上传如下,只需将image和imageFileName定义成数组型即可private File[] image;private String[] imageFileName;    以上

热点排行