우선, 우리는 Spring Boot가 무엇인지 알아야합니다. 여기에 대해 간단히 얘기하겠습니다. Spring Boot는 프레임 워크에서 프레임 워크로 간주 될 수 있습니다 .-> 보안, JPA, 데이터, 클라우드 등과 같은 다양한 프레임 워크를 통합합니다. 구성에 신경 쓰지 않아도되며 개발을 신속하게 시작할 수 있습니다. 관심이 있으시면 자동화 된 구성 구현 원리를 이해할 수 있습니다. 본질적으로, 그것은 Spring 4.0의 조건부 구성 구현입니다. 베팅을 깊게 떠나면 볼 수 있습니다.
스프링 부팅 파일 업로드의 원리는 실제로 스프링 MVC입니다.이 작업 의이 부분은 스프링 부팅이 아닌 스프링 MVC에 의해 수행되기 때문입니다. 그렇다면 SpringMVC는 파일 업로드 프로세스를 어떻게 처리합니까?
그림:
먼저, 프로젝트가 관련 구성을 시작한 다음 위의 두 번째 단계를 수행하면 Dispatcherservlet은 Multipartresolver의 ID로 Bean을 찾습니다. 구성에서 Bean은 Commonsmultipartresolve를 가리키며, 이는 Multipartresolver 인터페이스를 구현합니다.
여기서 네 번째 단계는 멀티 파트 파일이 Ismultipart 메소드인지 여부를 결정합니다. Return True : Multipartresolver 메소드가 호출됩니다. httpservletrequest를 통과하면 Multiparthttpservletrequest 객체를 반환 한 다음 Dispatcherservlet가 컨트롤러 계층으로 처리됩니다. 거짓 반환 : 무시되고 httpservletrequest를 계속 통과합니다.
MVC에서는 다음과 같이 구성 파일 WebApplicationContext.xml에서 구성해야합니다.
<bean id = "multipartresolver"> <property name = "defaultencoding"value = "utf-8"/> <property name = "maxuploadsize"value = "1000000000"/> <property name = "uploadtempdir"value = "FileUpload/temp"/> </bean>
Spring Boot가 자동으로 구성되었으며 직접 사용하면 테스트하는 데 아무런 문제가 없습니다. 기본 업로드 제한 크기가 있지만 실제 개발에서는 여전히 일부 구성을 만듭니다.
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 파일 업로드의 제 3자를 기반으로 구현됩니다. 이것은 또한 Servlet 3.0 이전입니다. 3.0+ 후에는 타사 라이브러리에 의존 할 수도 있습니다. 표준 ervletmultipartresolver를 사용할 수 있으며, 이는 멀티 패트 레졸버 인터페이스를 구현합니다. 구현을 볼 수 있습니다.
* Copyright 2002-2017 원래 저자 또는 저자 .Package org.springframework.web.multipart.support; import javax.servlet.http.httpservletrequest; import javax.servlet.http.part; import org.apache.commons.logging.logfactory; org.springframework.web.multipart.multipartexception; import org.springframework.web.multipart.multiparthttpservletrequest; import org.springframework.web.multipart.multipartresolver;/** @link grance it the stander it the the the the the the the the the the the the epander ubstance 3.0 {@link javax.servlet.http.part} api. * 스프링 디스패처 서비스 컨텍스트에 "Multipartresolver"Bean으로 추가됩니다. * Bean 레벨에서 추가 구성없이 (아래 참조). * * * <p> <b> 참고 : </b> Servlet 3.0 기반 멀티 파트 파싱을 사용하려면 * 영향을받는 서블릿을 * {@code web.xml}의 "multipart-config"섹션 또는 {@link javax.servlet.multipartconfigelement} * in Progratic Servlet registration, 또는 with with with with with with with with in a in a in a in a in a progrmatic {@link javax.servlet.annotation.multipartConfig} 주석 * 서블릿 클래스에서. 최대 크기 또는 * 스토리지 위치와 같은 구성 설정은 해당 서블릿 등록 수준에서 적용해야합니다. * Servlet 3.0은 멀티 패스트레 솔버 레벨에서 설정할 수 없습니다. * * * @Author Juergen Hoeller * @since 3.1 * @see #setResolvelazily * @see httpservletrequest #getParts () * @see org.springframework.web.web.multipart.commons.commonsmultipartresolver */public classedervletmultiptresolver antresolver antresolver resolvelazily = false; /** * * 파일 또는 매개 변수 액세스 시점에 멀티 파트 요청 게으른 요청을 게으르게 해결할지 여부를 설정합니다. * <p> 기본값은 "false"이며, {@link #ResolVemultIpart} 호출 시점에 해당 예외를 던지는 Multipart 요소를 즉시 해결합니다. * 게으른 멀티 파트 구문 분석의 경우 이것을 "true"로 전환하고, 구문 분석 예외를 던지십시오 * 응용 프로그램이 멀티 팩 파일 또는 매개 변수를 얻으려고 시도하면 *. */ public void setresolvelazily (부울 resolvelazily) {this.resolvelazily = resolvelazily; } @override public boolean ismultipart (httpservletrequest request) {// commons fileUpload와 동일한 점검 ... if ( "post".equals (request.getMethod (). tolowercase ())) {return false; } 문자열 contentType = request.getContentType (); return (contentType! = null && contentType.tolowerCase (). startSwith ( "multipart/")); } @override public theumparthttpservletrequest resolveMultipart (httpservletrequest 요청) multipartexception {return new 표준 multiparthttpservletrequest (return, request, this.resolvelazily); } @override public void cleanupmultipart (multiparthttpservletrequest request) {// 안전한 측면에있는 것 : // 부분을 명시 적으로 삭제하지만 실제 파일 부품 만 명시 적으로 삭제합니다 (수지 호환성) {for (part : request.getParts ()) {if (request.getname ())); }}} catch (Throwable ex) {logfactory.getLog (getClass ()). 경고 ( "멀티 파트 항목의 정리를 수행하지 못했습니다", ex); }}}다음은 이전에 쓴 테스트의 후자 구현 구성 클래스입니다. 이해하기 위해 간단히 살펴볼 수 있습니다.
package com.bj.config; import org.springframework.boot.autoconfigure.condition.conditionalonmissingbean; import org.spramframework.autoconfigure.web.multipartProperties; import org.springframewort.context.enableconproperties org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.sprameframework.web.multipart.multipartresolver; import org.springframework.web.support.sportserververververtmultipartresol org.springframework.web.servlet.dispatcherservlet; import javax.servlet.multipartconfigelement;@configuration@enableconfigurationProperties (multipartProperties.class) public class fileUploadconfig {privateuploadcoperties multiptroperties; public fileUploadConfig (multipartProperties multipartProperties) {this.multipartProperties = multipartProperties; } / *** Parser 등록* @return* / @bean (이름 = dispatcherservlet.multipart_resolver_bean_name) @ConditionalOnMissingBean (multipartresolver.class) public StandardservletservletMultipartresolver multipartresolver () {sporedardervletmultipartresoltresoltresol Vermultresoltresol Standardservletmultipartresolver (); multipartresolver.setResolvelazily (multipartProperties.isresolvelazily ()); 리턴 멀티 패트 레졸버; } / *** 구성 업로드 구성* @return* / @bean @conditionalOnMissingBean public multipartConfigelement multipartConfigElement () {return this.multipartProperties.createmultIpartConfig (); }}요약
위는 편집기가 소개 한 Spring Boot 파일 업로드의 원리입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!