码迷,mamicode.com
首页 > 其他好文 > 详细

Struts文件上传的大小及类型的限制

时间:2014-09-26 20:20:18      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   strong   文件   sp   

前几天讲到struts文件上传,设置了fileUpload拦截器的参数以后,超过大小的文件被限制上传,但是类型不匹配的,却没有得到限制,今天有时间找了一下原因,发表一篇博文,请遇到问题的同学,参考一下:

在struts-default.xml中可以看到fileUpload的拦截器对应的类org.apache.struts2.interceptor.FileUploadInterceptor,查看源码会发现,类中的几个属性:

 protected Long maximumSize;
    protected Set<String> allowedTypesSet = Collections.emptySet();
    protected Set<String> allowedExtensionsSet = Collections.emptySet();

其中:maximumSize为允许上传的单个文件的大小

allowedTypesSet 为允许上传类型的集合

allowedExtensionsSet为允许上传的扩展名的集合

于是就有了我的错误配置:

 

<!-- 文件上传 Action -->
        <action name="fileup" class="cn.bdqn.action.FileUpAction">
            <interceptor-ref name="fileUpload"><!-- 添加 文件上传 拦截器 设置 ,并添加参数 -->
                <param name="maximumSize">200000</param><!-- 单个文件大小 -->
                <param name="allowedExtensionsSet">html,txt</param><!-- 允许上传的文件扩展名 -->
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref><!-- 添加 默认 拦截器栈设置 , -->
            <param name="savePath">/upload</param>
            <result>up_success.jsp</result>
            <result name="input">testUp.jsp</result>
        </action>

我按照拦截器中的属性配置了拦截器的三个参数,出现的错误结果就是:

超过大小的文件被限制上传,但是类型不匹配的,却没有得到限制

今天仔细看了一个源码里,有三个方法:

   /**
     * Sets the allowed extensions
     *
     * @param allowedExtensions A comma-delimited list of extensions
     */
    public void setAllowedExtensions(String allowedExtensions) {
        allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);
    }

    /**
     * Sets the allowed mimetypes
     *
     * @param allowedTypes A comma-delimited list of types
     */
    public void setAllowedTypes(String allowedTypes) {
        allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);
    }

    /**
     * Sets the maximum size of an uploaded file
     *
     * @param maximumSize The maximum size in bytes
     */
    public void setMaximumSize(Long maximumSize) {
        this.maximumSize = maximumSize;
    }

于是,找到了错误,我们配置的拦截器的参数,应该根据set方法来,所以三个参数就应该是:maximumSize、allowedTypes和allowedExtensions

修改配置为:

<interceptor-ref name="fileUpload"><!-- 添加 文件上传 拦截器 设置 ,并添加参数 -->
                <param name="maximumSize">200000</param><!-- 单个文件大小 -->
                <param name="allowedExtensions">html,txt</param><!-- 允许上传的文件扩展名 -->
            </interceptor-ref>

测试,文件大小和扩展名的限制,成功!

 

Struts文件上传的大小及类型的限制

标签:style   blog   color   io   os   ar   strong   文件   sp   

原文地址:http://www.cnblogs.com/zhuaixia/p/3995141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!