首先我們要知道什麼是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中配置 如下:
而Spring Boot已經自動配置好,直接用就行,做個test沒什麼問題。有默認的上傳限制大小,不過在實際開發中我們還是做一些配置的,
如下在application.properties中:
# multipart config
#默認支持文件上傳
spring.http.multipart.enabled=true
#文件上傳目錄
spring.http.multipart.location=/tmp/xunwu/images/
#最大支持文件大小
spring.http.multipart.max-file-size=4Mb
#最大支持請求大小spring.http.multipart.max-request-size=20MB
當然也可以寫配置類來實現,具體的就不做展示了。
看完上述你肯定有個大概的瞭解了,這裡再囉嗦下,Spring提供Multipart的解析器:MultipartResolver,上述說的是CommonsMultipartResolver,它是基於Commons File Upload第三方來實現,這也是在Servlet3.0之前的東西,3.0+之後也可以不需要依賴第三方庫,可以用StandardServletMultipartResolver,同樣也是實現了MultipartResolver接口,我們可以看下它的實現:
* Copyright 2002-2017 the original author or authors.
package org.springframework.web.multipart.support;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
/**
* Standard implementation of the {@link MultipartResolver} interface,
* based on the Servlet 3.0 {@link javax.servlet.http.Part} API.
* To be added as "multipartResolver" bean to a Spring DispatcherServlet context,
* without any extra configuration at the bean level (see below).
*
*
Note: In order to use Servlet 3.0 based multipart parsing,
* you need to mark the affected servlet with a "multipart-config" section in
* {@code web.xml}, or with a {@link javax.servlet.MultipartConfigElement}
* in programmatic servlet registration, or (in case of a custom servlet class)
* possibly with a {@link javax.servlet.annotation.MultipartConfig} annotation
* on your servlet class. Configuration settings such as maximum sizes or
* storage locations need to be applied at that servlet registration level;
* Servlet 3.0 does not allow for them to be set at the MultipartResolver level.
*
* @author Juergen Hoeller
* @since 3.1
* @see #setResolveLazily
* @see HttpServletRequest#getParts()
* @see org.springframework.web.multipart.commons.CommonsMultipartResolver
*/
public class StandardServletMultipartResolver implements MultipartResolver {
private boolean resolveLazily = false;
/**
* Set whether to resolve the multipart request lazily at the time of
* file or parameter access.
*
Default is "false", resolving the multipart elements immediately, throwing
* corresponding exceptions at the time of the {@link #resolveMultipart} call.
* Switch this to "true" for lazy multipart parsing, throwing parse exceptions
* once the application attempts to obtain multipart files or parameters.
*/
public void setResolveLazily(boolean resolveLazily) {
this.resolveLazily = resolveLazily;
}
@Override
public boolean isMultipart(HttpServletRequest request) {
// Same check as in Commons FileUpload...
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
}
@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
return new StandardMultipartHttpServletRequest(request, this.resolveLazily);
}
@Override
public void cleanupMultipart(MultipartHttpServletRequest request) {
// To be on the safe side: explicitly delete the parts,
// but only actual file parts (for Resin compatibility)
try {
for (Part part : request.getParts()) {
if (request.getFile(part.getName()) != null) {
part.delete();
}
}
}
catch (Throwable ex) {
LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
}
}
}
這裡是之前寫的test的後者實現配置類,可以簡單看下,作為了解:
package com.bj.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.web.MultipartProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.MultipartConfigElement;
@Configuration
@EnableConfigurationProperties(MultipartProperties.class)
public class FileUploadConfig {
private final MultipartProperties multipartProperties;
public FileUploadConfig(MultipartProperties multipartProperties){
this.multipartProperties=multipartProperties;
}
/**
* 註冊解析器
* @return
*/
@Bean(name= DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
@ConditionalOnMissingBean(MultipartResolver.class)
public StandardServletMultipartResolver multipartResolver(){
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(multipartProperties.isResolveLazily());
return multipartResolver;
}
/**
* 上傳配置
* @return
*/
@Bean
@ConditionalOnMissingBean
public MultipartConfigElement multipartConfigElement(){
return this.multipartProperties.createMultipartConfig();
}
}
加Java架構師進階交流群獲取Java工程化、高性能及分佈式、高性能、深入淺出。高架構。性能調優、Spring,MyBatis,Netty源碼分析和大數據等多個知識點高級進階乾貨的直播免費學習權限 都是大牛帶飛 讓你少走很多的彎路的 群.號是:338549832 對了 小白勿進 最好是有開發經驗
注:加群要求
1、具有工作經驗的,面對目前流行的技術不知從何下手,需要突破技術瓶頸的可以加。
2、在公司待久了,過得很安逸,但跳槽時面試碰壁。需要在短時間內進修、跳槽拿高薪的可以加。
3、如果沒有工作經驗,但基礎非常紮實,對java工作機制,常用設計思想,常用java開發框架掌握熟練的,可以加。
4、覺得自己很牛B,一般需求都能搞定。但是所學的知識點沒有系統化,很難在技術領域繼續突破的可以加。
5.阿里Java高級大牛直播講解知識點,分享知識,多年工作經驗的梳理和總結,帶著大家全面、科學地建立自己的技術體系和技術認知!
閱讀更多 java開發者 的文章