struts2文件上传
总结struts2文件上传的代码编写
以上传图片文件为例
form表单:
form表单中的enctype属性为: enctype="multipart/form-data"
使用struts2标签 <s:fielderror></s:fielderror>
显示提示信息,如提示上传文件太大或者上传文件格式不正确。
<FORM id=add_action method="post" action="addImage.action" enctype="multipart/form-data">
<TR>
<TD class=field>图 片:</TD>
<TD>
<INPUT id=add_action_price class=text type="file" name="image">
</TD>
</TR>
<TR>
<td>
<INPUT value=立即发布 type="submit">
<s:fielderror></s:fielderror>
</td>
</FORM>
struts2为我们提供了默认的提示信息在struts2的核心jar包中可以找到。点开struts2-core-2.2.1.jar,找到org.apache.struts2并点开。找到struts-messages.properties,点开会看到:
struts.messages.error.uploading=Error uploading: {0}
struts.messages.invalid.content.type=Could not find a Content-Type for {0}. Verify that a valid file was submitted.
struts.messages.error.file.too.large=File too large: {0} "{1}" "{2}" {3}
分别会提示:上传发生错误,上传文件类型不对,上传文件太大。
我们在src下配置自己的提示信息:
在src中新建xiaoxi.properties文件,如图:
然后需要在struts.xml中添加配置:
<constant name="struts.custom.i18n.resources" value="xiaoxi"></constant>
上传图片的input标签中name=”image”,所以我们在Action类中需要定义三个类属性分别是
//上传文件属性
private File image;
private String imageContentType;
private String imageFileName;
并提供set,get方法。
文件上传的位置为webRoot下的house_images
编写action请求调用的方法:
public String add() {
try {
//处理上传文件
String path = ServletActionContext.getRequest().getRealPath("/house_images/"+imageFileName);
//通过文件流的方式,把上传图片放到house_images中
FileInputStream fis = new FileInputStream(image);
FileOutputStream fos = new FileOutputStream(path);
//创建字节数组读取文件
byte[] temp = new byte[1024];
int size = -1;
do {
size = fis.read(temp);
if(size != -1) {
fos.write(temp, 0, size);
}
} while (size != -1);
fos.flush();
fos.close();
fis.close();
System.out.println("添加成功");
} catch (Exception e) {
e.printStackTrace();
return "exception";
}
return "add_success";
}
struts.xml配置上传拦截器栈指定允许上传的文件类型和文件大小:
<interceptor-stack name="uploadStack">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/gif</param>
<param name="maximumSize">102400</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
struts.xml配置上传成功后跳转的路径:
<action name="*Image" class="com.test.action.ImageAction">
<interceptor-ref name="uploadStack"></interceptor-ref>
<result name="add_success">/success.jsp</result>
</action>
运行程序跳转成功,打开tomcat7中webapps中项目经理根目录发现house_images中有上传的图片,说明图片上传成功。