Si construimos un pequeño sitio web y solo elegimos las pilas de tecnología de arranque de Kotlin y Spring, entonces cargar archivos es esencial. Por supuesto, si crea un sitio web medio y grande, se recomienda que use el almacenamiento en la nube, lo que puede ahorrar muchos problemas.
Este artículo presenta cómo usar Kotlin y Spring Boot para cargar archivos
Proyecto de construcción
Si no está muy familiarizado con el proyecto de construcción, puede consultar "mi primera aplicación Kotlin"
Archivo build.gradle completo
Grupo 'name.quanke.kotlin'version' 1.0-snapshot'buildscript {ext.kotlin_version = '1.2.10' ext.spring_boot_version = '1.5.4.Release' Repositorios {mavencentral ()} dependencias {classpath "org.jetbrains.kotlin: kotlin-gradle--opllin: $ thierntlin: $" classpath ("org.springframework.boot: spring-boot-gradle-plugin: $ spring_boot_version") // Kotlin integra el constructor de parámetros predeterminado de SpringBoot, y establece todas las clases para abrir el complemento de clase classpath ("org.jetbrains.kotlin: kotlin-noarg: $ kotlin_version") classpath ("org.jetbrains.kotlin: kotlin-allopen: $ kotlin_version")}} Aplicar complemento: 'kotlin'apply plugin: "kotlin-spring" // consulte https://kotlinlang.org/docs/refers/compiler-plugins.html#kotlin Plugin: 'org.springframework.boot'jar {BaseName =' Capítulo11-5-6-seservice 'versión =' 0.1.0 '} Repositorios {mavencentral ()} dependencias {compilar "org.jetbrains.kotlin: kotlin-stdlib-jre8: $ kotlin_version" compilarse " "org.springframework.boot: spring-boot-starter-web: $ spring_boot_version" compile "org.springframework.boot: spring-boot-starter-thymeleaf: $ spring_boot_version" testCompile "org.springfrframework.boot: torto-boot-starter-test: "org.jetbrains.kotlin: kotlin-test-junit: $ kotlin_version"} compilekotlin {kotlinoptions.jvmtarget = "1.8"} compiletkotlin {kotlinoptions.jvmtarget = "1.8"}Crear controlador de carga de archivos
importar nombre.quanke.kotlin.chaper11_5_6.storage.storageFilenotfoundExceptionImport name.quanke.kotlin.chaper11_5_6.storage.storageserviceImport org.springframework.beans.factory.annotation.autowiredImport Org.springframework.core.io.ResourceMport org. org. java.util.stream.collectores/*** Controlador de carga de archivos* Creado por http://quanke.name el 2018/1/12. */ @ControllerClass FileUploadController @AUTOWIREDConstructor (private val storageService: storageService) {@getmapping ("/") @throws (ioexception :: class) diversión listupploadedFiles (model: model): string {model.addattribute ("files", storageService. MvCuriComonentsBuilder .FromMethodName (fileUploadController :: class.java, "ServFile", Path.Filename.ToString ()) .Build (). ToString ()} .Collect (Collectors.tolist ())) Returning "LoadForm"} @getMappes ("/files/{{{{{{{{{{{{{ @ResponseBody Fun ServFile (@PathVariable FileName: String): ResponseEntity <RonceSce> {val file = storageService.LoadAsResource (nombre de archivo) returnedsEntity .Ok () .Header (httpheaders.content_disposition, "Adjunta; nombre de archivo =/" " + Filename +"/""). @PostMapping ("/") Fun HandleFileUpload (@RequestParam ("File") Archivo: MultipartFile, redirectAtTributes: redirectAtTributes): string {storageService.store (file) redirectatTributes.addflashAttribute ("mensaje", "usted está con éxito" + file.ReniginalFilFilFilFilFilFilfilFilfilfilFilFilFilFileName! ") "Redirect:/"} @ExceptionHandler (StorageFileNotFoundException :: Class) Fun HandLestorageAnceRfilenotFound (exc: StorageFilenotFoundException): ResponseEntity <*> {return ResponseEntity.notFound (). Build <Any> ()}}La interfaz para cargar el servicio de archivo
importar org.springframework.core.io.resourceImport org.springframework.web.multipart.multipartFileMport java.nio.file.pathImport java.util.stream.streaminterface storageservice {sting initin () stread (archivo: multipartFile) Fun LoadAsresource (nombre de archivo: cadena): recursos de diversión deleteall ()}Servicio de archivo de carga
importar org.springframework.beans.factory.annotation.aUtowiredImport org.springframework.core.io.resourceImport org.springframework.core.io.urlresourceImport Org.springFrameWork.stereotype.serviceImport Org.springFramework.util.filesyseportSworkswork.stereotype.serviceImport Org.springFrameWork.Util.filesySportilswork.stereotype.serviceImport Org.springFrameWork.util.filesySportilSworksworkSporteType.ServiceImport Org.springFramework.util. org. java.nio.file.standardCopyOptionImport java.util.stream.stream@serviceclassySystemStoraGesService @aUtoWiredConstructor ( filename = stringUtils.cleanPath (file.originalFileName) try {if (file.isEmpty) {throw storageException ("no se puede almacenar el archivo vacío" + nombre de archivo)} if (filename.contains ("..")) {// Este es un cheque de seguridad de throwing storageException ("no puede almacenar el archivo con ruta relativa fuera de la directora" + filename)} files. this.rootlocation.resolve (nombre de archivo), StandardCopyOption.replace_Existing)} Catch (e: ioException) {Throw StorageException ("Error al almacenar el archivo" + nombre de archivo, e)}} anule la diversión loadAll (): stream <path> {intent {return Files.Walk (this.rootlation, 1) .filter } .map {ruta -> this.rootlocation.relativize (path)}} catch (e: ioException) {throw storageException ("Se pudo leer archivos almacenados", e)}} anular Fun Load (FileName: String): Path {returnLocation.resole (FileName)} anveride loadasResResResReseurce (FileName: string stredye: string {vale {vale {Valce {ValCe {ValCe {ValCe {ValCe {ValCe {ValCe {ValCe {ValCe {Vale {ValCe {ValCe {Vale {Vale {Vale {Vale {ValCe { Load (FileName) val recource = urlResource (file.touri ()) return if (resource.exists () || resource.iseadable) {resource} else {throw storageFileNotFoundException ("no se puede leer el archivo:" + nombre de archivo)}}}}} e: malformedurexception) {throLing storagefilenotfoundxception ("no se puede reinar el archivo)}}} (e: malformeMedureCeption) {showlefilenotfilexception (" no se puede leer el archivo ("no puede ser el nombre de archivo). }} anular diversión deleteall () {filesSystemUtilss.deleterCursive (rootLocation.tofile ())} anverride diversh init () {try {files.createedirectorories (rootLocation)} catch (e: ioException) {tirar almacenamientoxception ("no podría inicializar el almacenamiento", e)}}}Excepciones personalizadas
Open Class StorageException: RuntimeException {Constructor (Mensaje: String): Super (Mensaje) Constructor (Message: String, Cause: Throwable): Super (Mensaje, Causa)} Class StorageFilenotFoundException: StorageException {Constructor (Mensaje: String): Super (Message) Constructor (Mensaje: String, Cause: Trowable): Super (Message)}Directorio de carga de archivo de configuración
importar org.springframework.boot.context.properties.configurationproperties@configurationProperties ("Storage") Class StorageProperties { / ** * Ubicación de la carpeta para archivos de almacenamiento * / var ubicación = "cargar"}Iniciar bota de primavera
/*** Creado por http://quanke.name el 2018/1/9. */ @Springbootapplication @enableConfigurationProperties (StorageProperties :: Class) Aplicación de clases {@Bean Interner Fun init (storageService: storageService) = commandLinerUnner {storageService.DelEdealL () storaService.init ()} objeto complementario {@throws (excepción: class) @jvmstatic fun main (args) {SpringApplication.run (Application :: Class.Java, *Args)}}}Cree una plantilla HTML simple SRC/Main/Resources/Templates/uploadform.html
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {Message}"/> <//port> <div> <div método = "post" enctype = "multipart/formal-data" Action = "/"> <tave> <tr> subiendo: </td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <tr> <td> </td> <td> <input type = "enviar" valor = "cargar"/> </td> </tr> </box> </form> </div> <div> <li> <li th: cada = "file: $ {file> th: href = "$ {file}" rel = "externo nofollow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>Aplicación del archivo de configuración.yml
Primavera: http: multipart: tamaño máximo de archivo: 128kb max-request-size: 128kb
Para obtener más contenido relacionado con Boot Spring y Kotlin, siga "Boot de primavera y batalla práctica de Kotlin"
Código fuente:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
referirse a:
https://spring.io/guides/gs/uploading-files/
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.