Struts2_单文件上传
Struts2_单文件上传
第一步:在WEB-INF/lib下加入commons-fileupload-x.x.x.jar、commons-io-x.x.x.jar。这两个文件可以从 第二步:把form表的enctype设置为:"multipart/form-data",如下:
第三步: 在Action类中添加以下属性: private File image;// 得到上传的文件 private String imageFileName;// 得到文件的名称 private String imageContentType;// 得到文件的类型 public String execute() throws IOException { String realpath = ServletActionContext.getServletContext().getRealPath("/images"); System.out.println(realpath); if (image != null) { // images/ File savefile = new File(new File(realpath), imageFileName); if (!savefile.getParentFile().exists()) { savefile.getParentFile().mkdir(); } FileUtils.copyFile(image, savefile); ActionContext.getContext().put("message", "上传成功"); } return "success"; }package cn.itcast.g_action;import java.io.File;import java.io.IOException;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;// 得到文件的名称 private String imageContentType;// 得到文件的类型 public String getImageContentType() { return imageContentType; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } 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 execute() throws IOException { String realpath = ServletActionContext.getServletContext().getRealPath("/images"); System.out.println(realpath); if (image != null) { // images/ File savefile = new File(new File(realpath), imageFileName); if (!savefile.getParentFile().exists()) { savefile.getParentFile().mkdir(); } FileUtils.copyFile(image, savefile); ActionContext.getContext().put("message", "上传成功"); } return "success"; }}
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>