Wenn wir eine kleine Website erstellen und einfach Kotlin- und Spring -Boot -Technologie -Stapel auswählen, ist das Hochladen von Dateien unerlässlich. Wenn Sie eine mittelgroße und große Website erstellen, wird natürlich empfohlen, Cloud -Speicher zu verwenden, was viel Ärger sparen kann.
In diesem Artikel wird vorgestellt, wie Sie Kotlin und Spring -Boot verwenden, um Dateien hochzuladen
Bauprojekt
Wenn Sie mit dem Konstruktionsprojekt nicht sehr vertraut sind, können Sie sich auf "meine erste Kotlin -Anwendung" beziehen.
Vervollständigen Sie Build.gradle -Datei
Gruppe 'name.quanke.kotlin'version' 1.0-snapshot'buildscript {ext.kotlin_version = '1.2.10' ext.spring_boot_version = '1.5.4.Release' Repositories {mavencental ()} Abhängigkeiten {Klassenpath "org. classPath ("org.springframework.boot: Spring-Boot-Gradle-Plugin: $ spring_boot_version") // Kotlin integriert Springboot-Standard-parameterlosen Konstruktor und setzt alle Klassen für das Open-Class-Plugin-Klassenpath ("org.jetbrains.kotlin: kotlin-noarg: $ kotlin_version")) classPath ("org.jetbrains.kotlin: kotlin-allopen: $ kotlin_version")}} Plugin anwenden: 'kotlin'apply plugin: "kotlin-sping" // siehe https://kotlinlang.org/docs/reference/compiler-Plugin.html#kotlin-ccompiler-Plugin.html#kotlin-ccompiler-plugin.htmtml#kotlin- 'org.springFramework.boot'jar {baseName =' Kapitel11-5-6-service 'Version =' 0.1.0 '} Repositories {mavencentral ()} Abhängigkeiten {kompile "org.jetbrains.kotlin: kotlin-stlib-jre8: $ kotlin_version" compile "compile" compile "compile" compile "compile" compile "compile" compile "compile" compile "compile" compile "compile" compile "compile" compile "compile" compile "compile. "org.springframework "org.jetbrains.kotlin: kotlin-test-junit: $ kotlin_version"} compileKotlin {kotlinoptions.jvmtarget = "1.8"} compiletestkotlin {kotlinoptions.jvmtarget = "1.8"}}Datei -Upload -Controller erstellen
name.quanke.kotlin.chaper11_5_6.storage.storageFilenotFoundExceptionImport Name.quanke.kotlin.Chaper11_5_6.Storage.StorageServiceImport org.springFringframework.Annotation.AntoWiredimport oderg.spingFramework.Onotation.AutoWiredimport oderg.spingFramework.core.OntationSourcedimport oderg.sping.spramework.cores.OntationSourceriredimport oderg.sping.spramework.cores.Antation.AndoWiredImport oderg.spramework.cores.OntationSourceRedimport oder org.springframework.http.httpheadersimport org.springframework.http.ResponseEntityImport org.springframework.steretype.Controllerimport org.springFramework.Ui.Modelimport Org.springFramework.Web.Bind.annotation. org.springframework.web.multipart.multipartFileMport org.springframework.web.servlet.mvc.method.Annotation.mvcuricomponentsBuilderMport java.util.stream.collectors/*** Datei -Upload -Controller* Erstellt von http://quanke.name am 2018/1/12. */ @ControllerClass FileUploadController @AutowiredConstructor (private ValageService: storageService) {@getMapping ("/") @throw (ioException :: class) Fun ListUploadedFiles (Modell: Modell): String {modell.addatribute ("Dateien", StorageDeDEdFiles. MvcUriComponentsBuilder .fromMethodName(FileUploadController::class.java, "serveFile", path.fileName.toString()) .build().toString() } .collect(Collectors.toList())) return "uploadForm" } @GetMapping("/files/{filename:.+}") @ResponseBody Fun servile (@patheVariable Dateiname: String): Antwortabschluss <ressourcen> {val File = storageService.loadasResource (Dateiname) return responses. @PostMapping("/") fun handleFileUpload(@RequestParam("file") file: MultipartFile, redirectAttributes: RedirectAttributes): String { storageService.store(file) redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.originalFilename + "!") return "Redirect:/"} @ExceptionHandler (StorageFilenotFoundException :: class) Fun HandlestorageFilenotFound (Exc: StorageFilenotFoundException): Antwortabteilung <*> {return responses.notfound ().Die Schnittstelle zum Hochladen des Dateidienstes
import org.springframework.core.io.resourceimerport org.springframework Fun LoadasResource (Dateiname: String): Ressourcenspaß deleteAll ()}
Dateidienst hochladen
import org.springframework.beans.factory.annotation.autowiredimport org.springframework.core.io.resourceimer org. org.springframework java.nio.file.standardCopyOptionImport java.util.stream.stream@serviceclass Dateisystemstorsservice @AutowiredConstructor (Eigenschaften: StorageProperties): StorageService {private vallooTLocation: Path. oder Dateien.Copy (Datei.inputStream, this.rootLocation.resolve (Dateiname), StandardCopyOption.replace_EXISTING)} catch (e: ioException) {throw -StorageException ("" fehlgeschlagen, Datei " + Datei zu speichern" + Datei, e)}} Überschreibung von Funlader (). Pfad -> Pfad! String): Resource { try { val file = load(filename) val resource = UrlResource(file.toUri()) return if (resource.exists() || resource.isReadable) { resource } else { throw StorageFileNotFoundException( "Could not read file: " + filename) } } catch (e: MalformedURLException) { throw StorageFileNotFoundException("Could not read file: " + filename, e) } } override fun deleteAll() { FileSystemUtils.deleteRecursively(rootLocation.toFile()) } override fun init() { try { Files.createDirectories(rootLocation) } catch (e: IOException) { throw StorageException("Could not initialize storage", e) } }}Benutzerdefinierte Ausnahmen
Öffnen Sie die Klasse StoryException: RunTimeException {Constructor (Nachricht: String): Super (Message) Konstruktor (Nachricht: String, Ursache: Wurfweise): Super (Nachricht, Ursache)} Klasse StorageFilenotFoundException: StoryException {Konstruktor (Nachricht: String): Super (Message) Constructor (Meldung: String, Ursache: Throwable): Super (Message):Konfigurationsdatei -Upload -Verzeichnis
importieren org.springframework.boot.context.properties.configurationProperties@configurationProperties ("Storage") Klasse StorageProperties { / ** * Ordnerspeicher für Speicherdateien * / var location = "upload-dir"}Start Spring Stiefel
/*** Erstellt von http://quanke.name am 2018/1/9. */@SpringBootApplication@EnableConfigurationProperties(StorageProperties::class)class Application { @Bean internal fun init(storageService: StorageService) = CommandLineRunner { storageService.deleteAll() storageService.init() } companion object { @Throws(Exception::class) @JvmStatic fun main(args: Array<String>) { SpringApplication.run (application :: class.java, *args)}}}Erstellen Sie eine einfache HTML -Vorlage SRC/Main/Ressourcen/Vorlagen/Uploadform.html
<html xmlns: th = "http://www.thymeleaf.org"> <body> <div th: if = "$ {message}"> <h2 th: text = "$ {message}"/> </div> <div> <form method = "post" cabled. Upload: </td> <td> <Eingabe type = "Datei" name = "Datei"/> </td> </tr> <tr> <td> </td> <td> <input type = "value =" upload "/> </td> </tr> </table> </Form> </div> <ul> <ul> <ul> <ul> <ul> <ul> <ul> <ul> <ul> <li -th: $ = $ · {{{div> <ul> <ul> <li th: $ = $ · {{ask. th: href = "$ {file}" rel = "externer nofollow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>Konfigurationsdatei application.yml
Frühling: http: Mehrfach: Max-Dateigröße: 128 KB Max-Request-Größe: 128KB
Weitere Inhalte in Spring Boot und Kotlin beziehen sich bitte "Spring Boot und Kotlin Practical Battle".
Quellcode:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
Siehe:
https://spring.io/guides/gs/uploading-files/
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.