struts2如何实现文件上传

来源:互联网 发布:tf卡写入数据错误 编辑:程序博客网 时间:2024/05/27 09:45

      文件上传是一个很普遍的功能,看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"。这样就实现了文件上传功能,很简单,大家可以试试。      


 


0 0
原创粉丝点击