您的位置:首页 > 编程语言 > Java开发

struts2如何实现文件上传

2014-10-27 13:12 344 查看
文件上传是一个很普遍的功能,看struts2怎么实现?

1.页面功能






2.jsp

其他的页面布局省略了,只写摊位布局图的代码

 <s:form id="form1" action="market_add" enctype="multipart/form-data" method="post" >
<td style="text-align: right"><label class="control-label">摊位布局图:  </label> </td>
<td class="controls" ><input type="file" id="file" name="image" />  </td>
</s:form>


3.action实现

private File image; //上传的文件
        private String imageFileName; //文件名称
        private String imageContentType; //文件类型

/**
* 添加市场信息
*
* @return
* @throws Exception
*/
public String add() throws Exception {

String realpath = ServletActionContext.getServletContext().getRealPath("/data");
//D:\apache-tomcat-6.0.18\webapps\struts2_upload\images

System.out.println("realpath: "+realpath);
if (image != null) {
File savefile = new File(new File(realpath), imageFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(image, savefile);
ActionContext.getContext().put("message", "文件上传成功");
}
model.setMarketImage(realpath);
model.setState("已加入");

marketService.save(model);
System.out.println("上传成功!");

return "list";
}


其中要注意form中要写enctype="multipart/form-data"。这样就实现了文件上传功能,很简单,大家可以试试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: