标签:
<from enctype="multipart/form-data" action="${pageContext.request.contextPath}/list.action" method="post" <input type="file" name="uploadImage"> </form>
package cn.itcast.action; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; public class HelloWorldAction { private File image; private String imageFileName; public String getImageFileName() { return imageFileName; } public void setImageFileName(String imageFileName) { this.imageFileName = imageFileName; } public File getImage() { return image; } public void setImage(File image) { this.image = image; } public String addUI(){ return "success"; } public String execute() throws Exception{ String realpath = ServletActionContext.getServletContext().getRealPath("/images");//得到文件保存的目录(文件的绝对路径) System.out.println(realpath); if(image!=null){ File savefile = new File(new File(realpath), imageFileName);//savefile是一个完整的文件路径 if(!savefile.getParentFile().exists()) savefile.getParentFile().mkdirs();//如果保存文件的目录不存在则创建目录 FileUtils.copyFile(image, savefile);//调用系统函数拷贝文件image到savefile中 ActionContext.getContext().put("message", "上传成功"); } return "success"; } }
4.struts.xml文件配置如下所示:
<struts> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <!--控制文件上传的大小--> <constant name="struts.multipart.maxSize" value="10701096"/> <package name="employee" extends="struts-default"> <action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}"> <result name="success">/WEB-INF/page/message.jsp</result> </action> </package> </struts>
标签:
原文地址:http://www.cnblogs.com/kailing-con/p/4196953.html