SpringMVC文件上传——bean的配置【org.springframework.web.multipart.commons.CommonsMultipartResolver】...

本文介绍了Spring MVC中如何配置CommonsMultipartResolver来处理文件上传,包括maxUploadSize、maxInMemorySize和defaultEncoding等属性的设置。解析是否延迟取决于resolveLazily属性,详细分析了其工作原理,并提供XML配置示例。
部署运行你感兴趣的模型镜像

一、简介

  Spring MVC支持一个通用的多路上传解析器CommonsMultipartResolver,在Spring的配置文件中对CommonsMultipartResolver Bean进行配置时,有一些可选的属性配置。

 


 

二、分析

  经过百度和查看SpringMVC的API文档都没有发现相关的详细配置介绍,无可奈何只能查看源代码寻找蛛丝马迹:

  在Spring配置文件applicationContext.xml中配置了CommonsMultipartResolver Bean后,按 “ Ctrl+鼠标左击 ‘org.springframework.web.multipart.commons.CommonsMultipartResolver’ ” 进入其源代码界面,而在源代码中并没有发现直接声明的如"maxUploadSize"这样的属性。

   经过仔细查看,在源代码中,CommonsMultipartResolver类上的注释上看到了相关表述(如下标红加大字体):

 1 /**
 2  * Servlet-based {@link MultipartResolver} implementation for
 3  * <a href="http://commons.apache.org/proper/commons-fileupload">Apache Commons FileUpload</a>
 4  * 1.2 or above.
 5  *
 6  * <p>Provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as
 7  * bean properties (inherited from {@link CommonsFileUploadSupport}). See corresponding
 8  * ServletFileUpload / DiskFileItemFactory properties ("sizeMax", "sizeThreshold",
 9  * "headerEncoding") for details in terms of defaults and accepted values.
10  *
11  * <p>Saves temporary files to the servlet container's temporary directory.
12  * Needs to be initialized <i>either</i> by an application context <i>or</i>
13  * via the constructor that takes a ServletContext (for standalone usage).
14  *
15  * @author Trevor D. Cook
16  * @author Juergen Hoeller
17  * @since 29.09.2003
18  * @see #CommonsMultipartResolver(ServletContext)
19  * @see #setResolveLazily
20  * @see org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver
21  * @see org.apache.commons.fileupload.servlet.ServletFileUpload
22  * @see org.apache.commons.fileupload.disk.DiskFileItemFactory
23  */
24 public class CommonsMultipartResolver extends CommonsFileUploadSupport
25         implements MultipartResolver, ServletContextAware {
26 ...

  可以看到,其中包含了"maxUploadSize", "maxInMemorySize" ,"defaultEncoding"三个可供在Bean中配置的属性:

  •  maxUploadSize :用于限制上传文件的最大尺寸,单位为字节;
  •  maxInMemorySize :读取文件到内存中最大的字节数(相当于缓存),默认是1024,单位为字节;
  •  defaultEncoding :表示请求的编码格式,默认为iso-8859-1。

  此外,在源代码中还可以发现包含了一个已声明的属性和相应的setter方法:

  属性:resolveLazily

1     private boolean resolveLazily = false;

  对应的setter方法:

 1     /**
 2      * Set whether to resolve the multipart request lazily at the time of
 3      * file or parameter access.
 4      * <p>Default is "false", resolving the multipart elements immediately, throwing
 5      * corresponding exceptions at the time of the {@link #resolveMultipart} call.
 6      * Switch this to "true" for lazy multipart parsing, throwing parse exceptions
 7      * once the application attempts to obtain multipart files or parameters.
 8      */
 9     public void setResolveLazily(boolean resolveLazily) {
10         this.resolveLazily = resolveLazily;
11     }

  因此,可以推断出,通过Spring的依赖注入功能,可以在Bean中配置和注入该属性,经过一番查询得知:

  •  resolveLazily :判断是否要延迟解析文件。当 resolveLazily为false(默认)时,会立即调用 parseRequest() 方法对请求数据进行解析,然后将解析结果封装到 DefaultMultipartHttpServletRequest中;而当resolveLazily为 true时,会在DefaultMultipartHttpServletRequest的initializeMultipart()方法调用parseRequest()方法对请求数据进行解析,而initializeMultipart()方法又是被getMultipartFiles()方法调用,即当需要获取文件信息时才会去解析请求数据,这种方式用了懒加载的思想。

 


 

 三、示例

  配置一个CommonsMultipartResolver Bean(XML):

     <!--配置文件上传使用解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 指定字符集为utf-8 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        
        <!-- 指定上传文件最大尺寸 -->
        <property name="maxUploadSize" value="10240"/>
        
        <!-- 指定文件载入内存大小 -->
        <property name="maxInMemorySize" value="1024"/>
        
        <!-- 设置延时解析文件 -->
        <property name="resolveLazily" value="true"/>
    </bean>

 


 

转载于:https://www.cnblogs.com/wangzhijun97/p/9451463.html

您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

package com.itheima.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer; import javax.servlet.Filter; @Configuration public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer { @Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(SpringMvcConfig.class); return ctx; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected WebApplicationContext createRootApplicationContext() { return null; } //改善编码乱码问题 protected Filter[] getServletFilters(){ CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); return new Filter[]{characterEncodingFilter}; } } package com.itheima.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration @ComponentScan("com.itheima.controller") @EnableWebMvc //开启springmvc的辅助功能 public class SpringMvcConfig{ @Bean("multipartResolver") public CommonsMultipartResolver multipartResolver(){ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("utf-8"); resolver.setMaxUploadSize(1024*1024); return resolver; } } package com.itheima.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class SpringWebSupport extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/"); super.addResourceHandlers(registry); } }
最新发布
09-29
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值