Если мы создадим небольшой веб -сайт и просто выберем стеки технологий Kotlin и Spring Boot, то загрузка файлов имеет важное значение. Конечно, если вы создаете средний и большой веб -сайт, рекомендуется использовать облачное хранилище, что может сэкономить много проблем.
Эта статья представляет, как использовать загрузку Kotlin и Spring для загрузки файлов
Строительный проект
Если вы не очень хорошо знакомы с проектом строительства, вы можете обратиться к «Моему первому приложению Kotlin».
Полный файл build.gradle
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: kotlinle-plugrindenties {classpath" org.jetbrains.kotlin: kotlinle-pligrindenties {classpath "ourg.jetbrains.kotlinlristr_cers-gradlindly {wrg.jetbrains.kotlinlrilr ClassPath ("org.springframework.boot: Spring-Boot-Gradle-Plugin: $ spring_boot_version") // Котлин интегрирует конструктор без параметра-по умолчанию Springboot и устанавливает все классы для открытия плагина класса ClassPath (" classpath ("org.jetbrains.kotlin: kotlin-allopen: $ kotlin_version")}} Применить плагин: 'kotlin'apply plugin: "kotlin-spring" // См. 'org.springframework.boot'jar {basename =' gupt11-5-6-service 'version =' 0.1.0 '} Репозитории {mavencentral ()} зависимости {compile "org.jetbrains.kotlin: kotlin-stdlib-jre8: $ kotlin_version" "org.springframework.boot: Spring-Boot-Starter-Web: $ spring_boot_version" compile "org.springframework.boot: spring-boot-starter-thymelef: $ spring_boot_version" testcompile " "org.jetbrains.kotlin: kotlin-test-junit: $ kotlin_version"} compilekotlin {kotlinoptions.jvmtarget = "1.8"} compiletestkotlin {kotlinoptions.jvmtarget = "1.8"}Создать контроллер загрузки файлов
Import name.quanke.kotlin.Chaper11_5_6.Storage.StorageFilenOtFoundExceptionImport name.quanke.kotlin.chaper11_5_6.storage.storageServiceimport org.springframework.beans.factory.annotation.autowiredimport org.springframework.core.resourceimport. org.springframework.http.httpheadersimport org.springframework.http.responseentityImport org.springframework.steretype.controllerimport org.springframe.annotation.Ute.modelimport org.spramework.web.bind.annotation. org.springframework.web.multipart.MultipartFileimport org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilderimport org.springframework.web.servlet.mvc.support.RedirectAttributesimport java.io.IOExceptionimport java.util.stream.collectors/*** Контроллер загрузки файла* Создан http://quanke.name на 2018/1/12. */ @Controlerclass fileuploadcontroller @autowiredConstructor (private val Storageservice: Storageservice) {@getMaping ("/") @Throws (ioException :: class) Fun ListUploadedFiles (Model: Model): string {model.AdTtribute ("files", storageService .ludgAll (). Mvcuricomponentsbuilder .frommethodName (fileuploadController :: class.java, "servfile", path.filename.tostring ()) .build (). ToString ()} .collect (collectors.tolist ()) return "uploadform"} @getmapping ("/letistame ()): @Responsebody Fun Servfile (@pathvariable fileename: String): responseentity <resource> {val file = Storageservice.loadasresource (filename) return response. @Postmapping ("/") fun harder -fileupload (@requestparam ("file") файл: multipluartfile, redirectattributes: redirectattributes): string {storageservice.store (file) redirectattributes.addflashattrube («Сообщение», «Вы успешно загружены» + файл. } @ExceptionHandler (StorageFilenOtFoundException :: Class) Fun HandlestorageFilenOtFound (Exc: StorageFilenOtFoundException): responseentity <*> {return responseStity.notFound (). Build <Any> ()}}}}}}}}}}}}}}}}}Интерфейс для загрузки службы файлов
Импорт org.springframework.core.io.resourceimport org.springframework.web.multipart.multipartfileimport java.nio.file.pathimport java.util.stream.streamInterface StorageServ {Fun init (file: file) Fun Loadall (). FUN LOADASResource (имя файла: String): ресурс Fun deleteall ()}Загрузите файловую службу
Импорт org.springframework.beans.factory.annotation.autowiredimport org.springframework.core.io.resourceimport org.springframework.core.io.urlresourceiMport org.springframework.stepytypymport.serviceimport org.springfor org.springframework.util.stringutilsimport org.springframework.web.multipart.multipartfileimport java.io.ioexceptionImport java.net.malformedurlexempreseimport java.nio.file.filesimport java.file.pathimport.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pile.pilesmport. java.nio.file.standardcopyoptionimport java.util.stream.stream@serviceclass fileStemstorageservice @autowiredConstructor (Свойства: storageProperties): Storageservice {Private Vallocation: Path init us in.rootlocation = Paths.get (Properties.location) wepAlfile (pail). ValEname = stringUtils.cleanpath (file.originalfilename) try {if (file.isempty) {throw storageexception («Не удалось сохранить пустой файл» + fileName)} if (fileName.contains ("..")) {// Это проверка безопасности. this.rootlocation.resolve (filename), standardcopyoption.replace_existing)} catch (e: ioexception) {throw storage exception ("не удалось сохранить файл" + filename, e)}} переопределить Fun Loadall (): Stream <Path> {try {return files.walk (this.rootlocation, 1). .map {path -> this.rootlocation.relativize (path)}} catch (e: ioexception) {throw storage exception ("не удалось считать хранимые файлы", e)}} переопределить забавную нагрузку (fileename: string): path {return rootlocation.resolve (fileName)} переопределить Fun LoadAsresource (fillenam Загрузить (fileName) val resource = urlresource (file.touri ()) return af (resource.exists () || resource.isradable) {resource} else {throw storagefilenotfoundexception («Неизчистить файл:« + fileName)}} Catch (e: malformedUrlexcesscept }} переопределить Fun deleteAll () {fileSystemutils.deletetereCursive (rootlocation.tofile ())} переопределить fun init () {try {files.createdirectories (rootlocation)} catch (e: ioExceptПользовательские исключения
Откройте класс Storage Exception: Runtimeexception {Constructor (сообщение: String): Super (сообщение) Constructor (Сообщение: Строка, причина: Throwable): Super (сообщение, причина)} класс StoragefilenOtFoundException: StorageException {Constructor (сообщение: String): Super (сообщение) Конструктор (Сообщение: Строка, причина: Throwable): Super (сообщение, причина)}}}}}}}}}}}Каталог загрузки файлов конфигурации
Import org.springframework.boot.context.properties.configurationProperties@configurationProperties ("Storage") Class StorageProperties { / ** * Местоположение папки для файлов хранения * / var location = "upload-dir"}Начать весенний ботинок
/*** Создано http://quanke.name 2018/1/9. */ @SpringBootApplication @enableConfigurationProperties (StorageProperties :: Class) Class Application {@Bean Internal Fun Init (StorageService: StorageService) = CommandLinerUnner {Storageservice.deleteall () StorageService.init ()} companys {@throws (execection :::: @JvmStatic.Init ()} commine obj {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 = "$ {сообщение}"/> </div> <div> <form method = "ectype =" multipart/form-data "action ="/"> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <pire> <plode> <pire> <pire> <pire> <prope" ectype = " upload: </td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <input type = "value =" upload "/> </td> </tr> </table> </form> </div> <vil> <ul> <li: wangy =" file: $ a fily: Th: href = "$ {file}" rel = "enformlolow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>Приложение файла конфигурации.yml
Весна: http: Multipart: Max-File-Size: 128KB Max-Request-Size: 128KB
Чтобы узнать больше о весенней загрузке и контенте, связанном с котлин, следуйте "Spring Boot и Kotlin Practical Battle"
Исходный код:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
См.
https://spring.io/guides/gs/uploading-files/
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.