步骤:
(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>