Pig*_*ras 1 java validation struts2 file-upload
我有一个应用程序,可以让你上传一些照片.我有一个带有表单的jsp页面,用于选择要上传的照片:
苏比尔-foto.jsp
...
<s:form action="SubirFoto" method="post" enctype="multipart/form-data" theme="bootstrap">
<s:file name="foto" label="Foto" />
<s:submit value="Upload" align="center" />
</s:form>
...
Run Code Online (Sandbox Code Playgroud)
我希望使用此表单,用户只能上传某些类型的文件(如jpg,gif ...),并且不允许用户上传大小超过2 MB的照片.
在struts.xml
<action
name="SubirFoto"
class="impl.redex.presentation.profile.upload.SubirFotosAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="dentroStack"></interceptor-ref>
<result name="success">/WEB-INF/jsps/foto/foto-subida.jsp</result>
<result name="input">/WEB-INF/jsps/foto/subir-foto.jsp</result>
</action>
Run Code Online (Sandbox Code Playgroud)
除了一件事,文件上传工作完美.如果满足要求,我可以上传任何照片.如果我尝试上传不是照片的文件(例如,纯文本文件),应用程序会将我global.properties
在jsp形式的输入中定义的错误.
global.properties
struts.messages.error.uploading - No se ha podido subir el fichero
struts.messages.error.file.too.large - El fichero es demasiado grande. El tamaño máximo es de 2MB.
struts.messages.error.content.type.not.allowed - Tipo de fichero no aceptado. Sólo es válido si la foto \
está en formato jpg/jpeg, gif o png.
Run Code Online (Sandbox Code Playgroud)
问题是,如果我尝试上传大于2 MB的图像,应用程序会将我重定向到subir-foto.jsp,但它不会在jsp页面中放置任何错误.
我已经尝试了一下,如果我<s:actionerror />
在上传大照片时放入subir-foto.jsp,它会出现:
the request was rejected because its size (17224595) exceeds the configured maximum (2097152)
Run Code Online (Sandbox Code Playgroud)
如您所见,这不是我定义的错误global.properties
.
为什么这两个不同的错误字段错误?这是bootstrap插件的问题吗?或者它是Struts2的错误?难道我做错了什么?任何帮助,谢谢,谢谢.
我在谷歌搜索更多,我发现了一个解释错误的博客(博客文章来自2008年,我使用的是Struts 2.3.4):
http://blog.bielu.com/2008/09/solution-to-struts2-upload-file-error.html
我总结了如何解决我的问题.问题是消息the request was rejected because its size ...
是在一个Struts2类中硬编码的.
这个问题至少有三个解决方案(所有这些都是痛苦的屁股):一个是重新实现
org.apache.struts2.dispatcher.multipart.MultiPartRequest
课程; 第二个是重新实施org.apache.struts2.interceptor.FileUploadInterceptor
课程.
第三个是validate
在FileUpload类中放置一个方法.
@Override
public void validate() {
boolean error = false;
Collection<?> tmp = getActionErrors();
for (Object o : tmp) {
if (o.toString().contains(
"the request was rejected because its size")) {
if (!error) {
addFieldError("foto",
"El tamaño de la foto es muy grande (Máximo: 2MB)");
error = true;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,我仍然无法理解为什么我定义的消息不起作用,因为在我搜索的所有网站中都告诉我覆盖struts.messages.error.file.too.large
或为什么两个错误都有不同类型的错误(字段和操作错误).
感谢大家的时间.