由于当时写Demo时,是在原来的HelloWorld 上改,所以类名没有改过来。
Action类的代码主如下
/**
*
*/
package com.demo.view.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
/**
* @author Administrator
*
*/
public class HelloWorld {
private File image;
private String imageFileName;
private String imageContentType;
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 getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public String getHello(){
return "success";
}
public String upload() throws IOException{
String realPath=ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(realPath);
if(null!=image){
File saveFile=new File(new File(realPath),imageFileName);
if(!saveFile.getParentFile().exists()){
saveFile.getParentFile().mkdirs();
}
FileUtils.copyFile(image,saveFile);
ServletActionContext.getRequest().setAttribute("message", "文件上传成功");
}
return "success";
}
}
struts.xml配置文件
<struts>
<package name="myDemo" namespace="/demo" extends="struts-default">
<action name="helloWorld_*" class="com.demo.view.action.HelloWorld" method="{1}">
<result name="success">
/WEB-INF/pages/hello.jsp
</result>
</action>
</package>
</struts>
jsp页面
<body>
<form action="helloWorld_upload" method="post" enctype="multipart/form-data">
文件:<input type="file" name="image"><br>
<input type="submit" value="上传">
</form>
${message }
</body>