Si nous construisons un petit site Web et que nous choisissons simplement des piles de technologie de démarrage Kotlin et Spring, le téléchargement de fichiers est essentiel. Bien sûr, si vous créez un site Web moyen et grand, il est recommandé d'utiliser le stockage cloud, ce qui peut éviter beaucoup de problèmes.
Cet article présente comment utiliser Kotlin et Spring Boot pour télécharger des fichiers
Projet de construction
Si vous n'êtes pas très familier avec le projet de construction, vous pouvez vous référer à "Ma première application Kotlin"
Fichier complet de build.gradle
Groupe 'name.quanke.kotlin'version' 1.0-snapshot'buildscript {ext.kotlin_version = '1.2.10' ext.spring_boot_version = '1.5.4.4 ClassPath ("org.springframework.boot: Spring-Boot-Gradle-Plugin: $ printemps_boot_version") // Kotlin intègre le constructeur paramètre sans paramètre de Springboot, et définit toutes les classes pour ouvrir le plugin de classe ClassPath ("org.jetbrains.kotlin: Kotlin-noarg: $ kotlin_version") CLASSPATH ("org.Jetbrains.kotlin: Kotlin-Allopen: $ Kotlin_version")}} Appliquer Plugin: 'Kotlin'Apply Plugin: "Kotlin-spring" // voir https://kotlinlang.org/docs/reference/combinplugins.htmlin Plugin: 'org.springframework.boot'jar {basename =' Chapter11-5-6-Service 'version =' 0.1.0 '} Repositories {mavencentral ()} dépendances {compile "org.Jetbrains.kotlin: Kotlin-stdlib-jre8: $ kotlin_version" Compile "org.springframework.boot: printemps-boot-starter-web: $ printemps_boot_version" compile "org.springframework.boot: printemps-boot-starter-thymeleaf: $ printemps_boot_version" "org.jetbrains.kotlin: kotlin-test-junit: $ kotlin_version"} compilekotlin {kotlinoptions.jvmtarget = "1.8"} compiletestkotlin {kotlinoptions.jvmtarget = "1.8"}Créer un contrôleur de téléchargement de fichiers
importer name.quanke.kotlin.chaper11_5_6.storage.storagefilenotfoundExceptionImport name.quanke.kotlin.chaper11_5_6.storage.storageservicemport org.springframework.beans.factory.anotation.autowiredImport Org.springFramework.Core.io org.springframework.http.httpheadersIMPORT org.springframework.http.ResponseentityImport org.springframework.stereType.Controllerimport org.springframework.ui.modeLIMPOR org.springframework.web.multiparpart.multupartfileimport org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilderimport.redIrectAtwork.web.servlet.mvc.support.redIrectAtTRIBUTES java.util.stream.collectors / ** * Contrôleur de téléchargement de fichiers * créé par http://quanke.name le 2018/1/12. * / @ CONTRILERCLASS FileUploadController @AutowiredConstructor (private val storageService: StorageService) {@getMapping ("/") @Throws (ioException :: class) Fun listUploadedFiles (modèle: modèle): String {model.addattribute ("fichiers", storageShipOnl .FrommethodName (fileUploadController :: class.java, "ServeFile", path.filename.tostring ()) .build (). toString ()} .collect (collectionners.tolist ())) return "uploadform"} @getMapping ("/ file / {filename:. +}") FileName: String): ResponseNtity <Source> {val file = StorageService.LoadasResource (FileName) return réponse. handleFileUpload (@RequestParam ("File") Fichier: multipartFile, redirectattributes: redirectattributes): string {stocageservice.store (file) redirectattributes.addflashattribute ("message", "vous avez réussi à télécharger" + file.originalfilename + ") @ExceptionHandler (StorageFileNotFoundException :: class) Fun handleStorageFileNotFound (exc: StorageFileNotFoundException): Responsentity <*> {return réponsentity.notFound (). Build <yy> ()}}L'interface de téléchargement du service de fichiers
import org.springframework.core.io.resourceimport org.springframework.web.multiparpart.multipartfileimport java.nio.file.pathimport java.util.stream.streaminterface storageservice {fun init () Fun Store (File: multipartfile fun loadall (): Stream> Fun charge (filename: Filename): Path Fonde Loadall (): Stream> Fun Charge (FiderAname: Filename): Path Fun Loadal LoadAsResource (nom de fichier: chaîne): Resource Fun DeleteAl ()}Télécharger le service de fichiers
import org.springframework.beans.factory.annotation.AutowiredImport org.springframework.core.io.resourceImport org.springframework.core.io.urlresourceimport org.springframework.util.stringutilsimport org.springframework.web.multiparpart.multipartfileimpport java.io.ioexceptionmport java.net.malformedUrlexceptionImport java.nio.file.filesimport java.file java.nio.file.standardCopyOptionImport java.util.stream.stream@serviceClass FileSystemStorageService @AutowiredConstructor (Properties: StorageProperties): StoringService {private Val RootLocation: Path Init {this.rootLocation = Paths.get (Properties.LOLOCATION) filename = stringUtils.cleanPath (file.originalFileName) try {if (file.isempty) {throw StorageException ("a échoué pour stocker le fichier vide" + nom de fichier)} if (fileName.ConTains ("..")) {// Il s'agit d'un chèque de sécurité TROME STOCKERException ("Impossible de stocker un fichier avec un disqueur relatif, le répertoire actuel" + filename)} this.rootlocation.resolve (nom de fichier), standardCopyOption.replace_existing)} catch (e: ioException) {throw StorageException ("Échec du fichier" + nom de fichier, e)}} override fun lostall (): stream <path> {try {return files.walk (this.rootlocation, 1). .map {path -> this.rootlocation.relatiVize (path)}} catch (e: ioException) {throw StorageException ("a échoué à lire les fichiers stockés", e)}} Override Fun Load (nom de fichier: String): Path {return rootLocation.Resolve (FileName)} Override loadSesource (filename: string): ressource {Try File-override loadSesource (filename: string): ressource {Try Fidre = Val FondeSresource (filename: string): ressource {Try Fidre = Val Fonde. Load (nom de fichier) Val Resource = urlResource (file.touri ()) return if (ressource.exists () || Resource.isReadable) {Resource} else {throw StorageFilenotFoundException ("n'a pas pu lire le fichier:" + FileNAM }} Override Fun DeleteAll () {FilesystemUtils.deleterErecursively (rootLocation.tofile ())} Override Fun init () {try {Files.CreateDirectories (RootLocation)} Catch (e: ioException) {Throw StorageException ("n'a pas pu initialiser le stockage", e)}}}}Exceptions personnalisées
Open Class StorageException: RuntimeException {Constructeur (message: String): Super (message) Constructeur (message: chaîne, Cause: Thrownable): Super (message, Cause)} Class StorageFilenotFoundException: StorageException {Constructeur (Message: String): Super (message) Constructeur (Message: String, Cause: Lognable): Super (Message)}Répertoire de téléchargement de fichiers de configuration
Importer org.springframework.boot.context.properties.configurationproperties@configurationproperties ("Storage") Class StorageProperties {/ ** * Emplacement du dossier pour les fichiers de stockage * / var location = "upload-dir"}Démarrer la botte de printemps
/ ** * Créé par http://quanke.name le 2018/1/9. * / @ SpringbootApplication @ perteConfigurationProperties (StorageProperties :: class) class Application {@Bean Internal Fun init (StorageService: StorageService) = CommandLinerUnner {StorageService.DeleTeTeLl () StorageService.init ()} Objet Companion {@hrows (exception :: class) @jvmstatic SpringApplication.Run (application :: class.java, * args)}}}Créez un modèle HTML simple SRC / Main / Resources / Templates / UploadForm.html
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {message}" /> </ div> <div> <form methethy = "post" Enctype = "multipart / form data" Action = "/"> <bout> upload: </td> <td> <input type = "file" name = "file" /> </td> </tr> <tr> <td> </td> <td> <input type = "soumi" value = "upload" /> </td> </tr> </ Table> </ Form> </div> <iv> <ul> <li th: every = "file: file {fichiers}"> <a th: href = "$ {file}" rel = "external nofollow" th: text = "$ {file}" /> </li> </ul> </div> </ body> </html>Fichier de configuration Application.yml
Spring: HTTP: MultipART: Max-File-Size: 128KB MAX-Request-Size: 128KB
Pour plus de contenu lié à Spring Boot et Kotlin, veuillez suivre "Spring Boot et Kotlin Practical Battle"
Code source:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
se référer à:
https://spring.io/guides/gs/uploading-files/
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.