Struts2上传文件的一些配置
原创
©著作权归作者所有:来自51CTO博客作者请你打开电视看看的原创作品,请联系作者获取转载授权,否则将追究法律责任
限制上传文件大小
在default.xml中 文件上传大小默认设置为2M
struts.multipart.maxSize=2097152
报错:Request exceeded allowed size limit! Max size allowed is: 209,715,2 but request was: 641,743,1!
在struts.xml更改文件上传大小
<!-- 设置上传文件最大值 20M-->
<constant name="struts.multipart.maxSize" value="20971520"></constant>
限制上传类型
在struts-default,xml中 我们可以看到struts默认的拦截器中有一个fileUpload 实现他的是名为FileUploadInterceptor拦截器
内置有两个参数
allowedTypesSet 和 allowedExtensionsSet
可以通过在action中配置过滤器的参数实现文件类型的限制
<package name="U1" extends="struts-default" namespace="/user">
<action name="register" class="org.ccit.com.web.action.UserAction" method="register">
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedTypes">image/png,image/jpeg</param>
<!-- <param name="fileUpload.allowedExtensions">png,jpg</param>-->
</interceptor-ref>
<result name="input">/register.jsp</result>
<result name="success">/login.jsp</result>
</action>
</package>
allowedTypes报错:
Content-Type not allowed: photo “jquery-3.3.1.js” “upload_5da6724f_d41f_418b_b28e_177e5fed4c0b_00000000.tmp” text/javascript
allowedExtensions报错:
File extension not allowed: photo “jquery-3.3.1.js” “upload_5da6724f_d41f_418b_b28e_177e5fed4c0b_00000003.tmp” text/javascript
报错中文显示
在struts2-core-2.5.26.jar!\org\apache\struts2\struts-messages.properties中设定了个别语言的报错信息
可以创建properties文件 更改报错信息 并在struts.xml中配置prpperties文件
在src目录下创建FileUploadError.properties文件
struts.messages.error.content.type.not.allowed= {1}类型错误!
struts.messages.error.file.extension.not.allowed={1}类型错误!
struts.messes.upload.error.SizeLimitExceededException=上传文件过大 文件大小最大为{1}byte!
配置全局资源文件
<constant name="struts.custom.i18n.resources" value="FileUploadError"></constant>
多文件上传
1,将封装类中的三个属性改为数组类型
/**
* @program: struts2_03
* @description
* @author: LIANG
* @create: 2021-01-22 12:43
**/
public class User {
private String username;
private String password;
private File photo[];
private String photoFileName[];
private String photoContentType[];
//+get set toString
2,jsp页面添加文件上传组件
<s:form action="register" namespace="/user" enctype="multipart/form-data">
<s:file name="photo" label="头像1" ></s:file>
<s:file name="photo" label="头像2" ></s:file>
<s:file name="photo" label="头像3" ></s:file>
<s:textfield name="username" label="用户名" requiredLabel="true" requiredPosition="left"></s:textfield><br>
<s:password name="password" label="密码" requiredLabel="true" showPassword="true"></s:password><br>
<s:submit value="注册" ></s:submit>
</s:form>