查看: 283|回复: 0

[Java学习] Spring Boot 文件上传原理解析

发表于 2018-4-15 08:00:01

首先我们要知道什么是Spring Boot,这里简单说一下,Spring Boot可以看作是一个框架中的框架--->集成了各种框架,像security、jpa、data、cloud等等,它无须关心配置可以快速启动开发,有兴趣可以了解下自动化配置实现原理,本质上是 spring 4.0的条件化配置实现,深抛下注解,就会看到了。

  说Spring Boot 文件上传原理 其实就是Spring MVC,因为这部分工作是Spring MVC做的而不是Spring Boot,那么,SpringMVC又是怎么处理文件上传这个过程的呢?

  图:

  首先项目启动相关配置,再执行上述第二步的时候 DispatcherServlet会去查找id为multipartResolver的Bean,在配置中看到Bean指向的是CommonsMultipartResolve,其中实现了MultipartResolver接口。

  第四步骤这里会判断是否multipart文件即isMultipart方法,返回true:就会调用 multipartResolver 方法,传递HttpServletRequest会返回一个MultipartHttpServletRequest对象,再有DispatcherServlet进行处理到Controller层;返回false:会忽略掉,继续传递HttpServletRequest。

  在MVC中需要在配置文件webApplicationContext.xml中配置 如下:

  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  2. <property name="defaultEncoding" value="UTF-8"/>
  3. <property name="maxUploadSize" value="100000000"/>
  4. <property name="uploadTempDir" value="fileUpload/temp"/>
  5. </bean>
复制代码

  而Spring Boot已经自动配置好,直接用就行,做个test没什么问题。有默认的上传限制大小,不过在实际开发中我们还是做一些配置的,

如下在application.properties中:

  1. # multipart config
  2. #默认支持文件上传
  3. spring.http.multipart.enabled=true
  4. #文件上传目录
  5. spring.http.multipart.location=/tmp/xunwu/images/
  6. #最大支持文件大小
  7. spring.http.multipart.max-file-size=4Mb
  8. #最大支持请求大小
  9. spring.http.multipart.max-request-size=20MB
复制代码

当然也可以写配置类来实现,具体的就不做展示了。

  看完上述你肯定有个大概的了解了,这里再啰嗦下,Spring提供Multipart的解析器:MultipartResolver,上述说的是CommonsMultipartResolver,它是基于Commons File Upload第三方来实现,这也是在Servlet3.0之前的东西,3.0+之后也可以不需要依赖第三方库,可以用StandardServletMultipartResolver,同样也是实现了MultipartResolver接口,我们可以看下它的实现:

  1. * Copyright 2002-2017 the original author or authors.
  2. package org.springframework.web.multipart.support;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.Part;
  5. import org.apache.commons.logging.LogFactory;
  6. import org.springframework.web.multipart.MultipartException;
  7. import org.springframework.web.multipart.MultipartHttpServletRequest;
  8. import org.springframework.web.multipart.MultipartResolver;
  9. /**
  10. * Standard implementation of the {[url=home.php?mod=space&uid=17823]@LINK[/url] MultipartResolver} interface,
  11. * based on the Servlet 3.0 {@link javax.servlet.http.Part} API.
  12. * To be added as "multipartResolver" bean to a Spring DispatcherServlet context,
  13. * without any extra configuration at the bean level (see below).
  14. *
  15. * <p><b>Note:</b> In order to use Servlet 3.0 based multipart parsing,
  16. * you need to mark the affected servlet with a "multipart-config" section in
  17. * {[url=home.php?mod=space&uid=24691]@code[/url] web.xml}, or with a {@link javax.servlet.MultipartConfigElement}
  18. * in programmatic servlet registration, or (in case of a custom servlet class)
  19. * possibly with a {@link javax.servlet.annotation.MultipartConfig} annotation
  20. * on your servlet class. Configuration settings such as maximum sizes or
  21. * storage locations need to be applied at that servlet registration level;
  22. * Servlet 3.0 does not allow for them to be set at the MultipartResolver level.
  23. *
  24. * @author Juergen Hoeller
  25. * @since 3.1
  26. * @see #setResolveLazily
  27. * @see HttpServletRequest#getParts()
  28. * @see org.springframework.web.multipart.commons.CommonsMultipartResolver
  29. */
  30. public class StandardServletMultipartResolver implements MultipartResolver {
  31. private boolean resolveLazily = false;
  32. /**
  33. * Set whether to resolve the multipart request lazily at the time of
  34. * file or parameter access.
  35. * <p>Default is "false", resolving the multipart elements immediately, throwing
  36. * corresponding exceptions at the time of the {@link #resolveMultipart} call.
  37. * Switch this to "true" for lazy multipart parsing, throwing parse exceptions
  38. * once the application attempts to obtain multipart files or parameters.
  39. */
  40. public void setResolveLazily(boolean resolveLazily) {
  41. this.resolveLazily = resolveLazily;
  42. }
  43. @Override
  44. public boolean isMultipart(HttpServletRequest request) {
  45. // Same check as in Commons FileUpload...
  46. if (!"post".equals(request.getMethod().toLowerCase())) {
  47. return false;
  48. }
  49. String contentType = request.getContentType();
  50. return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
  51. }
  52. @Override
  53. public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
  54. return new StandardMultipartHttpServletRequest(request, this.resolveLazily);
  55. }
  56. @Override
  57. public void cleanupMultipart(MultipartHttpServletRequest request) {
  58. // To be on the safe side: explicitly delete the parts,
  59. // but only actual file parts (for Resin compatibility)
  60. try {
  61. for (Part part : request.getParts()) {
  62. if (request.getFile(part.getName()) != null) {
  63. part.delete();
  64. }
  65. }
  66. }
  67. catch (Throwable ex) {
  68. LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
  69. }
  70. }
  71. }
复制代码

这里是之前写的test的后者实现配置类,可以简单看下,作为了解:

  1. package com.bj.config;
  2. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  3. import org.springframework.boot.autoconfigure.web.MultipartProperties;
  4. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.web.multipart.MultipartResolver;
  8. import org.springframework.web.multipart.support.StandardServletMultipartResolver;
  9. import org.springframework.web.servlet.DispatcherServlet;
  10. import javax.servlet.MultipartConfigElement;
  11. @Configuration
  12. @EnableConfigurationProperties(MultipartProperties.class)
  13. public class FileUploadConfig {
  14. private final MultipartProperties multipartProperties;
  15. public FileUploadConfig(MultipartProperties multipartProperties){
  16. this.multipartProperties=multipartProperties;
  17. }
  18. /**
  19. * 注册解析器
  20. * @return
  21. */
  22. @Bean(name= DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
  23. @ConditionalOnMissingBean(MultipartResolver.class)
  24. public StandardServletMultipartResolver multipartResolver(){
  25. StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
  26. multipartResolver.setResolveLazily(multipartProperties.isResolveLazily());
  27. return multipartResolver;
  28. }
  29. /**
  30. * 上传配置
  31. * @return
  32. */
  33. @Bean
  34. @ConditionalOnMissingBean
  35. public MultipartConfigElement multipartConfigElement(){
  36. return this.multipartProperties.createMultipartConfig();
  37. }
  38. }
复制代码

总结

以上所述是小编给大家介绍的Spring Boot 文件上传原理解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对程序员之家网站的支持!



回复

使用道具 举报