Struts2是根据contentType来限制的,并不是文件的扩展名
比如想仅上传image/png,image/gif,image/jpeg这三种文件类型,如下两种方法:
a). 配置fileupload拦截器.Struts2的defaultStack中已经含有fileUpload拦截器,如果想加入allowedTypes参数,需要从新写一个defaultstack ,拷贝过来修改一下即可:
<interceptor-stack name="myDefaultStack"> <interceptor-ref name="exception"/> <interceptor-ref name="alias"/> <interceptor-ref name="servletConfig"/> <interceptor-ref name="i18n"/> <interceptor-ref name="prepare"/> <interceptor-ref name="chain"/> <interceptor-ref name="debugging"/> <interceptor-ref name="profiling"/> <interceptor-ref name="scopedModelDriven"/> <interceptor-ref name="modelDriven"/> <interceptor-ref name="fileUpload"> <param name="allowedTypes"> image/png,image/gif,image/jpeg </param> </interceptor-ref> <interceptor-ref name="checkbox"/> <interceptor-ref name="staticParams"/> <interceptor-ref name="actionMappingParams"/> <interceptor-ref name="params"> <param name="excludeParams">dojo\..*,^struts\..*</param> </interceptor-ref> <interceptor-ref name="conversionError"/> <interceptor-ref name="validation"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> <interceptor-ref name="workflow"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
struts.xml中仅需修改:
<interceptor-ref name="fileUpload"> <param name="allowedTypes"> image/png,image/gif,image/jpeg </param> </interceptor-ref> <!-- maximumSize (可选) :这个拦截器允许的上传到action中的文件最大长度(以byte为单位). 注意这个参数和在webwork.properties中定义的属性没有关系,默认2MB allowedTypes (可选) : 以逗号分割的contentType类型列表(例如text/html),这些列表是这个拦截器允许的可以传到action中的contentType.如果没有指定就是允许任何上传类型. -->
b). jsp页面定义如下(testFileUpload.jsp)
<s:form action="testFileUpload" method="post" enctype="multipart/form-data"> <s:file name="file"theme="simple"/> <s:fielderror name="file"></s:fielderror> <s:submit/> </s:form>
参考:http://www.blogjava.net/landor2004/archive/2009/06/11/281416.html