struts中的文件上传
1、上传页面代码
<body>
<form action="file" enctype="multipart/form-data" method="post">
图片上传}:<input type="file" name="image">
<br/>
<input type="submit" value="提交">
</form>
</body>
2、struts.xml里面action配置
<action name="file" class="com.edu.hpu.action.FileAction"> <result>/fileuploadsuccess.jsp</result> </action>
3、FileAction
package com.edu.hpu.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileAction extends ActionSupport {
private File image;
/**
* 使用规范:
* imageFileName:image(前面文件的名字) + FileName(固定写法)
*/
private String imageFileName;
@Override
public String execute() throws Exception {
//获得文件存储路径
String path = ServletActionContext.getServletContext().getRealPath("/images");
//创建相应文件对象
File saveFile = new File(new File(path),imageFileName);
System.out.println(saveFile);
//创建文件存路径
if(!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
//保存文件
FileUtils.copyFile(image, saveFile);
return super.execute();
}
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;
}
}
4、结果展示页面
<body>
文件<s:property value="imageFileName"/>,上传成功!
</body>