struts2单个文件上传
form表单:
<form action="<%=basePath%>upload!upload.action"
enctype="multipart/form-data" method="post">
选择文件<input type="file" name="file" /> <input type="submit"
value="上传文件" />
</form>
action类:
private File file;
private String fileFileName;
private String uploadfileContentType;
public String upload() throws IOException {
String realpath = ServletActionContext.getServletContext().getRealPath(
"/upload"); //获得路径
if (file != null) {
File savefile = new File(new File(realpath), fileFileName);//获得文件地址
if (!savefile.getParentFile().exists()) //判断文件是否存在
savefile.getParentFile().mkdirs(); //创建目录
FileUtils.copyFile(file, savefile); //保存文件
ActionContext.getContext().put("message", "文件上传成功"); 把message信息传送到页面上
return "success";
}
return "fail";
}
接收信息页面上:
<body>
${message}
</body>
struts.xml配置略
form表单:
<form action="<%=basePath%>upload!upload.action"
enctype="multipart/form-data" method="post">
选择文件<input type="file" name="file" /> <input type="submit"
value="上传文件" />
</form>
action类:
private File file;
private String fileFileName;
private String uploadfileContentType;
public String upload() throws IOException {
String realpath = ServletActionContext.getServletContext().getRealPath(
"/upload"); //获得路径
if (file != null) {
File savefile = new File(new File(realpath), fileFileName);//获得文件地址
if (!savefile.getParentFile().exists()) //判断文件是否存在
savefile.getParentFile().mkdirs(); //创建目录
FileUtils.copyFile(file, savefile); //保存文件
ActionContext.getContext().put("message", "文件上传成功"); 把message信息传送到页面上
return "success";
}
return "fail";
}
接收信息页面上:
<body>
${message}
</body>
struts.xml配置略
本文介绍了一个使用Struts2框架实现单个文件上传的例子,包括表单设置、Action类处理逻辑及文件保存过程。通过具体代码展示了如何利用Struts2进行文件上传,并给出了一种简单有效的文件保存方案。

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



