对于struts2文件上传之前写过一个,是通过struts.properties的配置实现的,现在将配置信息改到了struts.xml中,一样可以成功了。
实现对文件上传类型,文件大小上限,保存文件绝路路径参数注入action。
上传jsp页面:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>发微博</title>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
-
- </head>
-
- <body style="font-size:14px;">
- <h2>写微博 <a href="index.jsp">返回首页</a></h2>
- <form action="upload" method="post" enctype="multipart/form-data">
- <textarea name="sayMessage" rows="4" cols="50"></textarea><br>
- 发文件<input name="upload" type="file"/><input type="submit" value="发微博">
- </form>
- <s:fielderror></s:fielderror>
- </body>
- </html>
struts2.xml文件中顶部常量配置部分:
- <!-- 配置文件上传时临时文件存放路径,我测试的过程中没配,报错说该项为空。 -->
- <constant name="struts.multipart.saveDir" value="E:\UploadFileDemo\tmp"></constant>
- <!-- 设置上传大小上限:200M -->
- <constant name="struts.multipart.maxSize" value="209715200"></constant>
- <!-- 指定资源文件 -->
- <constant name="struts.custom.i18n.resources" value="ApplicationResource"></constant>
struts2.xml文件中action部分:
- <action name="upload" class="myFileUploadAction">
- <result name="success">/index.jsp</result>
- <result name="input">/saymessage.jsp</result>
- <!--struts2默认只能上传2M文件,类型不限。 配置拦截器来限制上传文件的类型和大小 -->
- <interceptor-ref name="fileUpload">
- <!-- 限定文件上传类型 -->
- <param name="allowedTypes">image/png,image/x-png,image/jpg,image/pjpeg,image/bmp,image/gif</param>
- <!-- maximumSize指每个上传文件的大小上限,单位为:byte,这里设为30M,该值不能大于struts.multipart.maxSize总大小 -->
- <param name="maximumSize">31457280</param>
- </interceptor-ref>
- <!-- 默认拦截器栈 -->
- <interceptor-ref name="defaultStack"></interceptor-ref>
- <!-- 注入文件上传路径参数到myFileUploadAction中 -->
- <param name="savePath">E:\\UploadFileDemo</param>
-
- </action>
文件上传action代码:
ApplicationResource.properties资源文件
- #Generated by ResourceBundle Editor (http://eclipse-rbe.sourceforge.net)
-
- login.user.password = \u5BC6\u7801
- login.user.password.invalid = \u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A
- login.user.userId = \u7528\u6237\u540D
- login.user.userId.invalid = \u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A
- #\u66F4\u6539\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B\u4E0D\u5141\u8BB8\u7684\u63D0\u793A\u4FE1\u606F
- struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6\u7C7B\u578B\u4E0D\u88AB\u5141\u8BB8
- #\u66F4\u6539\u4E0A\u4F20\u6587\u4EF6\u592A\u5927\u7684\u63D0\u793A\u4FE1\u606F
- struts.messages.error.file.too.large=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u60A8\u4E0A\u4F20\u7684\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u4E0A\u9650\uFF0830M\uFF09
- #\u6587\u4EF6\u4E0A\u4F20\u5176\u5B83\u9519\u8BEF\u4FE1\u606F
- struts.messages.error.uploading=\u6587\u4EF6\u4E0A\u4F20\u5931\u8D25\uFF0C\u4E0A\u4F20\u7A0B\u5E8F\u53D1\u751F\u5185\u90E8\u9519\u8BEF
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。