STRUTS2 文件上传

步骤:

(1)在JSP页面的form的enctye设订为multipart/form-data

<body>
<s:form enctype="multipart/form-data" action="fileuploadAction">
<input type="file" name="robinfile"><br>
<s:submit value="上 传" />
</s:form>  </body>

(2)action中定义与提交JSP页面元素相同的file变量,对应的两个变量:名称和文件类型,struts2规定是在file变量名非别加“ContentType”和“Name”

	public String execute() throws Exception{
		try {
		String realPath = ServletActionContext.getServletContext().getRealPath("/image");
		System.out.println(realPath);
		File a = new File(realPath);
		if (!a.exists()) {
			a.mkdirs();
		}
		 
			FileUtil.copyFile(robinfile, new File(a,robinfileFileName));
			ActionContext.getContext().put("result", "success");
			System.out.println("success@@");
		} catch (Exception e) {
 			e.printStackTrace();
 			throw e;
		}
		
		return SUCCESS;
	}

(3)注:struts2默认的上传文件大小为(2097152byte 即2M),需要更改的话。需要在struts.xml中加入常量

<constant name="struts.multipart.maxSize" value=" ..... " />


也可以使用过滤器对单个action的上传大小进行控制

<action name="FileUpload" class="cn.timefly.strutsTest.FileUploadAction">
<result name="success">/FileUploadResult.jsp</result>
<result name="input">/FileUpload.jsp</result>
<interceptor-ref name="fileUpload">
      <param name="maximumSize">500000</param>
      <param name="allowedTypes">application/vnd.ms-powerpoint</param>    
    </interceptor-ref>
<interceptor-ref name="defaultStack" />
    </action>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值