前言
上一篇【SpringBoot深度探究(一)】模拟了一个SpringBoot启动Tomcat的过程,其核心技术就是Servlet3.0提供的SPI做的服务增强。这篇将会继续探究SpringBoot的其他核心功能。比如这篇博客要说的Multipart Resolver,主要用来做上传功能的模块,我们将会从解读Spring官网的使用样例说到为什么Spring要这样做。更多Spring内容进入【Spring解读系列目录】。
Spring MVC官网推荐的上传技术
官网推荐的上传技术简单来说就是MultipartResolver,对此【SpringMVC官网】上做了下面的说明,一共推荐了两种技术。
MultipartResolver from the org.springframework.web.multipart package is a strategy for parsing multipart requests including file uploads. There is one implementation based on Commons FileUpload and another based on Servlet 3.0 multipart request parsing.
MultipartResolver来自于org.springframework.web.multipart包,是一种解析复合请求的一种策略,包括文件上传。并且推荐了两种技术了两种上传技术:一种是基于实现Commons FileUpload,另外一种是基于Servlet3.0的符合请求解析。可见Servlet3.0做了相当大的更新,SPI的技术也是出自Servlet3.0版本。
To enable multipart handling, you need to declare a MultipartResolver bean in your DispatcherServlet Spring configuration with a name of multipartResolver. The DispatcherServlet detects it and applies it to the incoming request. When a POST with content-type of multipart/form-data is received, the resolver parses the content and wraps the current HttpServletRequest as MultipartHttpServletRequest to provide access to resolved parts in addition to exposing them as request parameters.
为了能够处理复合请求,用户需要在DispatcherServlet里面声明一个MultipartResolver的bean,并且在Spring配置中命名为multipartResolver(注:这个名字是固定不变的)。做好以后DispatcherServlet就可以探测到它并且应用它到进入的请求中。当收到一个POST请求的内容类型(content-type)是multipart/form-data的时候,解析器就会解析内容并把HttpServletRequest请求包装成为一个MultipartHttpServletRequest请求,以便提供对解析部分的访问,此外还会把他们作为请求参数暴露出去。
Apache Commons FileUpload
既然Spring官网提供了两种那么我们一个一个的看。先看Apache Commons FileUpload。
To use Apache Commons FileUpload, you can configure a bean of type CommonsMultipartResolver with a name of multipartResolver. You also need to have commons-fileupload as a dependency on your classpath.
官网大意是说要使用Apache Commons FileUpload,必须先配置一个叫做CommonsMultipartResolver的bean,并且这个这个bean要以multipartResolver命名。然后也需要一个commons-fileupload的依赖。
Commons FileUpload Sample
官网说的一笔带过,具体要怎么做呢,写个Sample具体说明一下。注:演示MultipartResolver的用法,会直接使用html做Sample。如果用JSP需要额外配置视图解析器,参考【SpringMVC新版本(Spring 5.3.0)官网详解(一)】中AppConfig的配置。
引入必要的依赖:
<!--Spring 上下文包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--Spring web依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!--servlet依赖-->
<dependency>
<gr

本文介绍了SpringBoot中的文件上传功能,包括MultipartResolver的作用及其实现方式。探讨了ApacheCommonsFileUpload与Servlet3.0技术在SpringMVC中的应用。
最低0.47元/天 解锁文章
1751

被折叠的 条评论
为什么被折叠?



