jar包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
//${pageContext.request.contextPath}根目录
<form action="${pageContext.request.contextPath}/test/helloworld" enctype="multipart/form-data" method="post"> //表单中属性要加上enctype="multipart/form-data"
<input type="file" name="image">
<input type="submit" value="ok">
</form>
package cn.action;
import java.io.File;import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class HelloWordAction {
private File image; //文件名称,与之前的表单中的<input type=“file” name="image" >的name相对应
private String imageFileName; //文件名称后+FileName表示上传文件的名称
private String imageContentType;
//文件名称后+ContentType表示上传文件的类型
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 Exception{
String path=ServletActionContext.getServletContext().getRealPath("/images"); //获取“/images”文件夹的真实路径
System.out.println(path);
if(image!=null){ //判断上传文件是否存在
File savepath=new File(new File(path),imageFileName ); //保存imageFileName到path目录底下
if(!savepath.getParentFile().exists()) //判断文件夹是否存在
savepath.getParentFile().mkdirs(); //创建文件夹
FileUtils.copyFile(image, savepath); //把image文件转存到savepath路径下,如果看不到FileUtils方法是因为没有导 //包commons-io-1.3.2.jar
System.out.println("保存成功");
ActionContext.getContext().put("aa", "保存成功");//给request范围赋值
}
return "success";
}
}
如果上传文件超过2MB,需要到struts2.xml中加上:<constant name="struts.multipart.maxSize" value="10701096"/>
//value里设置文件上传大小