작은 웹 사이트를 구축하고 Kotlin 및 Spring Boot Technology 스택을 선택하면 파일 업로드가 필수적입니다. 물론 중간 및 대형 웹 사이트를 구축하는 경우 클라우드 스토리지를 사용하여 많은 문제를 절약 할 수 있습니다.
이 기사는 Kotlin 및 Spring Boot를 사용하여 파일을 업로드하는 방법을 소개합니다.
건설 프로젝트
건설 프로젝트에 익숙하지 않은 경우 "My First Kotlin 응용 프로그램"을 참조하십시오.
완전한 빌드. 그레이드 파일
Group 'name.quanke.kotlin'version'1.0-snapshot'buildscript {ext.kotlin_version = '1.2.10'ext.spring_boot_version = '1.5.4. Release'Repositories {mavencentral ()} 종속 경로 {classpath "org.jetbrains.kotlin : kotlin-kotlugin : kotlin-gupgin. classPath ( "org.springframework.boot : spring-boot-gradle-plugin : $ spring_boot_version") // Kotlin은 SpringBoot의 기본 매개 변수가없는 생성자를 통합하고 모든 클래스를 클래스 플러그인 클래스 경로 ( "org.jetbrains.kotlin : Kotlin-Noarg : $ kotlin_version")로 설정합니다. classpath ( "org.jetbrains.kotlin : kotlin-allopen : $ kotlin_version")}}}} 플러그인 적용 : 'kotlin'Apply 플러그인 : "Kotlin-Spring"// https://kotlinlang.org/Reference/Compiler-plugins.html#kotlin-compoller-compoler-compontler-compoller-compoller-compontler-plugin 'org.springframework.boot'jar {basename ='챕터 11-5-6-service '버전 ='0.1.0 '} 저장소 {mavencentral ()} 종속성 {compile "org.jetbrains.kotlin : kotlin-stdlib-jre8 : $ kotlin_verson"compile. "org.springframework.boot : spring-boot-starter-web : $ spring_boot_version"compile "org.springframework.boot : spring-boot-starter-thymeleaf : $ spring_boot_version"testCompile "org.springframework.boot : spring-bboot-starter-test : $ spring_boot _"test-compire "org.jetbrains.kotlin : kotlin-test-junit : $ kotlin_version"} compilekotlin {kotlinoptions.jvmtarget = "1.8"} compiletestkotlin {kotlinoptions.jvmtarget = "1.8"}파일 업로드 컨트롤러를 만듭니다
가져 오기 이름 .quanke.kotlin.chaper11_5_6.storage.StorageFilenotFoundExceptionImport Name.quanke.kotlin.chaper11_5_6.storage.storageserviceimport org.springframework.bean.beans.annotation.autowiredimport org org.springframework.http.httppheadersimport org.springframework.http.responsentityimport org.springframework.steretype.controllerimport org.springframework.ui.modelimport org.springframework.bind.bind.bind.antation org.springframework.web.multipart.multipartfileimport org.springframework.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilderimport org.springframework.web.servlet.mvc.support.repport.reuctortimport Java.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.io.ioectemport java.util.stream.collectors/*** 파일 업로드 컨트롤러* http://quanke.name 2018/1/12에 의해 생성되었습니다. */ @controllerclass fileUploadController @autowiredConstructor (private val storagesErcice : storagesErfice) {@getMapping ( "/") @throws (ioException :: class) fun listuploadedFiles (model : model) : String {model.addattribute ( "files", storageService. .frommethodName (fileUploadController :: class.java, "servfile", path.filename.toString ()) filename : string) : responsentity <resource> {val file = storageService.loadAsresource (filename) return responseentity .ok () .Header (httpheaders.content_disposition, "첨부; filename =/" " + file.filename +"/"". handleFileUpload (@requestparam ( "file") 파일 : multipartfile, redirectattributes : redirectattributes) : string {storageservice.store (파일) redirectattributes.addflashattribute ( "메시지", "성공적으로 업로드 된" + 파일. @ExceptionHandler (StorageFilenotFoundException :: Class) Fun HandlestorageFilenotFound (Exc : StorageFilenotFoundException) : responseentity <*> {return responsenity.notFound (). 빌드 <Any> ()}}파일 서비스를 업로드하기위한 인터페이스
import org.springframework.core.io.resourceimport org.springframework.web.web.multipart.multipartfileimport Java.nio.file.Pile.Pile.Pile.Pile.Pile.PILE JAVA.util.stream.Streaminter StoragesErvice {fun init () fun road (filen) : filen : fun) loadAsResource (filename : String) : Resource Fun deleteall ()}파일 서비스를 업로드하십시오
import org.springframework.bean.beans.annotation.autowiredimport org.springframework.core.io.resourceimport org.springframework.core.io.urlresourceimport org.springframework.stereotyp.serviceimport org org.springframework.util.stringutilsimport org.springframework.web.multipart.multipartfileimport java.io.ioexceptionimport java.net.malformedurlexceptionimport java.nio.file.filesimport java.nio.file java.nio.file.standardcopyoptionimport java.util.stream.stream.stream@serviceclass pilesystemstoragesvice @autowiredconstructor (properties : stac filename = stringUtils.cleanPath (file.originalFilename) try {if (file.isempty) {Throw StorageException ( "빈 파일 저장" + filename)} if (filename.contains ( "") {// 보안 검사 스토리지 ecception ( " + filename)} 파일. this.rootlocation.resolve (filename), StandardCopyoption.replace_existing)} catch (e : ioException) {StorageException ( "파일을 저장 실패" + filename, e)} in funall ()를 지배합니다 () : stream <path> {return {return.walk (this.rootlocation, 1). .map {path-> this.rootlocation.relativize (path)}} catch (e : ioexception) {Throw StorageException ( "저장된 파일을 읽지 못했다", e)}} 재미있는로드 (filename : string) : path {return rootlocation.resolve (filename)} fun {string {string) : string : string). load (filename) val resource = urlresource (file.touri ()) return if (resource.exists () || resource.isreadable) {resource} else {wash stac }} fun fun deleteall () {filesystemutils.deleterEcursive (rootlocation.tofile ()) rement init init () {try {files.createdirectories (rootlocation)} catch (e : ioxception) {StorageException ( "초기화 할 수 없음", e)}}}}}}}}}}}}}}맞춤형 예외
Open Class StorageException : runtimeexception {runtimeexception {super (메시지) 생성자 (메시지 : 문자열, 원인 : 던질 가능) : Super (메시지, 원인)} class storageFilenotFoundException : storageException (메시지 : String) : Super (메시지 : String, Cause : Super, Cause)}}}}}}}}}}}}구성 파일 업로드 디렉토리
import org.springframework.boot.context.properties.configurationProperties@configurationProperties ( "Storage") 클래스 StorageProperties { / ** * 스토리지 파일의 폴더 위치 * / var location = "upload-dir"}스프링 부츠를 시작하십시오
/*** 2018/1/9에 http://quanke.name에 의해 만들어졌습니다. */ @springbootApplication @enableConfigurationProperties (stac SpringApplication.run (application :: class.java, *args)}}}
간단한 HTML 템플릿 SRC/Main/Resources/Templates/UploadForm.html을 만듭니다
<html xmlns : th = "http://www.thymeleaf.org"> <body> <div th : if = "$ {message}"> <h2 th : text = "$ {message}"/> </div> <form 메소드 = "multype ="multipart/form-data "action ="/"> 업로드 : </td> <td> <입력 유형 = "파일"이름 = "file"/> </td> </tr> <tr> <td> <td> <td> <입력 유형 = "value ="value = "upload"/> </td> </tr> </table> </form> <liv> <ul> <li th : $ {files : et. Th : href = "$ {file}"rel = "external nofollow"th : text = "$ {file}"/> </li> </ul> </div> </body> </html>구성 파일 application.yml
스프링 : HTTP : 멀티 파트 : 최대 파일 크기 : 128KB Max-Request-Size : 128kb
더 많은 Spring Boot 및 Kotlin 관련 콘텐츠를 보려면 "Spring Boot 및 Kotlin Practical Battle"을 따르십시오.
소스 코드 :
https://github.com/quanke/spring-boot-with-kotlin-in-action/
참조 :
https://spring.io/guides/gs/uploading-files/
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.