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裏設置文件上傳大小