struts2如何实现文件上传

      文件上传是一个很普遍的功能,看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
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值