파일 업로드는 인터넷의 일반적인 시나리오 중 하나입니다. 가장 일반적인 상황은 아바타 등을 업로드하는 것입니다. 오늘날 스프링 부팅에서 파일을 업로드하는 작은 사례를 수행하게됩니다.
1. POM 패키지 구성
Spring Boot의 최신 버전 1.5.9, JDK는 1.8, Tomcat8.0을 사용합니다.
<부모> <groupid> org.springframework.boot </groupid> <artifactid> Spring-Boot-Starter-Parent </artifactid> <bersion> 1.5.9. release </version> </parent> <properties> <java.version> 1.8 </java.version> </properties> <pelovemencies> <pelaxence> <groupid> org.springframework.boot </groupid> <artifactid> Spring-boot-starter-web </artifactid> </fectionency> <pectionement> <groupid> org.springframewort.boot </groupid> <artifactid> spring-boot-starter -themelef </expence> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-devtools </artifactid> <선택 사항> true </septional> </fectionency> </fectionements>
Spring-Boot-Starter-Thymeleaf는 페이지 템플릿 엔진으로 소개되어 간단한 업로드 예제를 작성합니다.
2. 스타트 업 클래스 설정
@SpringBootApplicationPublic Class FileUploadWebApplication {public static void main (String [] args)은 예외 {springApplication.run (fileUploadWebApplication.class, args); } // tomcat 대형 파일 업로드 연결 재설정 @Bean public tomcatembeddedServletContainerFactory tomCatembedded () {tomcatembeddedServletContainerFactory tomcat = 새로운 tomCatembeddedServletContainerFactory (); tomcat.addconnectorCustomizers ((TomCatConnectorCustomizer) Connector-> {if ((Connector.getProtocolHandler () ABSTRACTHTTTP11PROTOCOL <?>) {// -1은 무한한 의미 (AbsTracthTTTP11P11Protocol <?>) Connector (setProtocoller ()). }}); 반환 Tomcat; }}Tomcatembedded 코드는 10m보다 큰 파일을 업로드 할 때 연결 재설정 문제를 해결하는 것입니다. 이 예외 컨텐츠는 Globalexception에 의해 캡처되지 않습니다.
자세한 내용 참조 : Tomcat 대형 파일 업로드 연결 재설정
3. 프론트 엔드 페이지를 작성하십시오
페이지 업로드
<! docType html> <html xmlns : th = "http://www.thymeleaf.org"> <h1> 스프링 부팅 파일 업로드 예 </h1> <form 메소드 = "post"action = "/upload"entermype = "multipart/form-data"> input type = "file"/<brr. "/<brr." 타입 = "제출"값 = "제출"/> </form> </body> </html>
매우 간단한 사후 요청, 파일을 선택하는 선택 상자 및 제출 버튼은 다음과 같습니다.
결과 표시 페이지 업로드 :
<! docType html> <html lang = "en"xmlns : th = "http://www.thymeleaf.org"> <body> <h1> 스프링 부팅 - 업로드 상태 </h1> <div th : if = "$ {message}"> <h2 th : text = "$ {message}"/>렌더링은 다음과 같습니다.
4. 업로드 제어 클래스를 쓰십시오
LocalHost를 방문하여 자동으로 업로드 페이지로 이동하십시오.
@GetMapping ( "/") public String index () {return "upload";}서비스 처리 업로드
@postmapping ( "/upload") public string singlefileupload (@requestparam ( "file") multipartfile 파일, redirectattributes redirectattributes) {if (file.isempty ()) {redirectattributes.addflashattribute ( "message", upload로 파일을 선택하십시오 "); "리디렉션 : 업로드 스타 우스"를 반환합니다. } 시도 {// 파일을 가져 와서 바이트 어딘가에 저장하십시오 [] bytes = file.getBytes (); Path Path = Paths.get (uploaded_folder + file.getoriginalFilename ()); files.write (경로, 바이트); RedirectAttributes.AddFlashAttribute ( "메시지", "성공적으로 업로드 된 '" + file.getoriginalFilename () + "'"); } catch (ioexception e) {e.printstacktrace (); } "리디렉션 :/uploadstatus";} 반환위의 코드는 파일 정보가 멀티 파트 파일을 통해 읽히고 파일이 비어 있으면 결과 페이지로 이동하여 프롬프트를 제공 함을 의미합니다. 파일 스트림이 비어 있지 않고 지정된 디렉토리에 기록되면 결과가 페이지에 표시됩니다.
MultipartFile은 이진 스트림 및 파일 속성과 같은 정보를 포함하는 스프링 업로드 파일의 캡슐화 클래스입니다. 관련 속성은 구성 파일에서 구성 할 수도 있습니다. 기본 구성 정보는 다음과 같습니다.
spring.http.multipart.enabled = true #default 지원 파일 업로드 .spring.spring.http.multipart.file-size- threshold = 0 #support 파일 쓰기 Disk.spring.http.multipart.location = # spring.http.-multipart.maxile-size를위한 임시 디렉토리 = # spring.http.multipart.max-Request-size = 10MB # 최대 지원 요청 크기
가장 일반적으로 사용되는 것은 마지막 두 구성 내용으로 파일 업로드 크기를 제한합니다. 파일이 크기를 초과하면 업로드 할 때 예외가 발생합니다.
자세한 구성 정보는 여기를 참조하십시오 : 공통 응용 프로그램 속성
5. 예외 처리
@ControllerAdVicePublic Class GlobalExceptionHandler {@ExceptionHandler (multipartException.class) public String handerError1 (MultipartException e, RedirectAttributes RedirectAttributes) {redirectattributes.addflashattribute ( "메시지", e.getCause (); GetMessage (); "리디렉션 :/uploadstatus"를 반환합니다. }}Multipart에서 업로드 된 파일 크기가 제한되어 있는지 모니터링하려면 @controlleradvice를 설정하십시오. 이 예외가 발생하면 프론트 엔드 페이지에 프롬프트가 제공됩니다. 글로벌 통합 예외 처리 등과 같은 @ControllerAdvice로 많은 일을 할 수 있습니다. 관심있는 학생들은 이에 대해 배울 수 있습니다.
6. 요약
Spring Boot를 사용하여 파일 업로드의 간단한 데모가 완료되었습니다. 관심있는 학생들은 샘플 코드를 다운로드하여 시도 할 수 있습니다.
참조 :
샘플 코드 -github
샘플 코드 코드 클라우드
요약
위는 Spring Boot 파일 업로드 기능을 사용하여 편집기가 소개 한 것입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!