1、单文件上传:
在 struts.xml 中:
<package name="upload" namespace="/upload" extends="struts-default">
<action name="upload1" class="cn.itcast.action.UploadAction1" method="execute">
<result name="success">/success.jsp</result>
</action>
</package>在 UploadAction1 中:
public class UploadAction1 extends ActionSupport implements Serializable{
private File image; // 对应的就是表单中文件上传的那个输入域的名称,Struts2框架会封装成File类型
private String imageFileName; // 上传输入域 FileName 即文件名,拼写不能错。
private String imageContentType; // 文件上传的MIME类型
封装……
public String execute(){
try{
// 处理实际的上传代码
// 找到存储文件的真实路径
s.o.p( imageFileName );
s.o.p( imageContentType );
ServletContext sc = ServletActionContext.getServletContext();
String storePath = sc.getRealPath("/files");
// 另一种上传方法
FileUtils.copyFile( image, new File(storePath, imageFileName) );
ActionContext.getContext().put("message","上传成功");
return SUCCESS;
} catch(Exception e){
return ERROR;
}
}
} 在上传页面 upload.jsp 中
<form action="${pageContext.request.contextPath}/upload/upload1" method="post" enctype="multipart/form-data">
文件:<input type="file" name="image"><br/>
<input type="submit" value="上传">
</form>
本文介绍如何使用Struts2框架实现单文件上传功能,包括配置struts.xml,定义UploadAction处理上传逻辑,以及创建上传表单。通过具体代码示例展示了文件上传的全过程。
568

被折叠的 条评论
为什么被折叠?



