小さなWebサイトを構築し、KotlinとSpring Boot Technologyスタックを選択するだけで、ファイルのアップロードが不可欠です。もちろん、中程度および大規模なWebサイトを構築する場合は、クラウドストレージを使用することをお勧めします。これにより、多くのトラブルを節約できます。
この記事では、KotlinとSpring Bootを使用してファイルをアップロードする方法を紹介します
建設プロジェクト
建設プロジェクトにあまり慣れていない場合は、「私の最初のKotlinアプリケーション」を参照できます。
build.gradleファイルを完了します
グループ '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-gradle-plugin:$ kotlin_version" classpath( "org.springframework.boot:spring-boot-gradle-plugin:$ spring_boot_version") classpath( "org.jetbrains.kotlin:kotlin-noarg:$ kotlin_version")classpath( "org.jetbrains.kotlin:kotlin-allopen:$ kotlin_version")}} fipplageプラグイン: 'kotlin'applyプラグイン: "kotlin-sspring" // see https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-pluginapplyプラグイン: 'org.springframework.boot'jar {basename =' baster11-5-6-service 'バージョン=' 0.1.0 'deposirisis { {compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$ kotlin_version" compile "org.springframework.boot:spring-boot-starter-web:$ spring_boot_version" compile "org.springframework.boot "org.springframework.boot:spring-boot-starter-test:$ spring_boot_version" testcompile "org.jetbrains.kotlin:$ kotlin_version"} compilekotlin {kotlinoptions.jvtarget = "1.8"} compileteTotlin { kotlinoptions.jvmtarget = "1.8"}ファイルアップロードコントローラーを作成します
name.quanke.kotlin.chaper11_5_6.storage.storagefilenotfoundexceptionmport name.quanke.kotlin.chaper11_5_6.storage.storageerviceimport org.springframework.beans.factory.annotation.autowiredimport org.springframework.http.httpheadersimport org.springframework.http.responseentityimport org.springframework.stertype.controllerimport org.springframework.ui.ui.modelimport org.springframework.web.bind.notation springframework.web.multipart.multipartfileimport org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilderimport org.springframework.web.servlet.mvc. java.util.stream.collectors/***ファイルアップロードコントローラー* http://quanke.nameが2018/1/12に作成しました。 */ @controllerclass fileuploadcontroller @autowiredconstructor(private val storageservice:storageservice){@getmapping( "/")@throws(ioexception :: class)fun listuploadedfiles(モデル:モデル):string {model.addattribute( "files"、storageervice。 mvcuricomponentsbuilder .frommethodname(fileuploadcontroller :: class.java、 "servefile"、path.filename.tostring()).build()。toString()。 @responsebody fun servefile( @pathvariable filename:string):ResponseNtity <sorstice> {val file = storageservice.loadasResource(filename)RepresseNtity .ok().ok().ok(httpheaders.content_disposition、 "attachment;" attachment; filename =/"" + "/"/"/"/"/") handleFileupload(@RequestParam( "ファイル")ファイル:MultipArtFile、Redirectattributes:Redirectattributes:Redirectattributes):String {storageservice.store(file)redirectattributes.addflashattribute( "message"、 "" you you you courded " + file.originalfilename +" @exceptionHandler(StorageFileNotFoundException :: class)Fun HandLestorageFileNotFound(exc:StorageFileNotFoundException):ResponseNtity <*> {Return ResponseNtity.NotFound()。ファイルサービスをアップロードするためのインターフェイス
org.springframework.core.io.resourceimport org.springframework.web.multipart.multipartfileimport java.nio.file.pathimport java.util.stream.streaminterface storageservice {fun:fun:fun pats pat <pat> fun load()fun load()fun load()fun load()fun load()fun load() loadasresource(filename:string):リソースファンdeleteall()}ファイルサービスをアップロードします
org.springframework.beans.factory.annotation.autowiredimport org.springframework.core.io.resourceimport org.springframework.core.io.urlresourceimport org.springframework.stereotyme.servicemport org.springframework.utilwork.utl.ystemport springframework.util.stringutilsimport org.springframework.web.multipart.multipartfileimport java.io.ioexceptionimport java.net.malformedexceptimport java.nio.nio.file.filesimport java.nio. Java.nio.file.StandardCopyoptionimport Java.util.stream.stream.stream @serviceclass filesstystemstorageservice @autowiredconstructor(Properties:StorageProperties):Storageservice {private Val Rootlocation:Path init {this.rootlocation = paths.get(Path.lide) {val filename = stringutils.cleanpath(file.OriginalFileName)try {if(file.isempty){throw storeexception( "空のfile" + filename)} if(filename.contains( "..")){// files.copy(file.inputStream、this.rootlocation.resolve(filename)、StandardCopyoption.Replace_Existing)} catch(e:ioException){throw StorageException( "file" + fileName、e)}}}} wun loadalk override untride fun <path .filter {path-> path!= this.rootlocation} .map {path-> this.rootlocation.relativize(path)}} catch(e:ioexception){throw storeexception( "readed files files"、e)}}} override fun load:filename:wride.ride.ride(filen lid.rid.red.red.red. loadasresource(filename:string):resource {try {val file = load(filename)val resource = urlresource(file.touri())return if(resource.exists()|| resource.isreadable){resource} StorageFileNotFoundException( "File:" + filename、e)}} leteTeall(){filesystemutils.deleterecively(rootlocation.tofile())} usride fun fun(){try {files.createdirecerties(rootlocation)} catch(e:ioexceprayise(e:io excections){e:files.createdirecertice) }}}カスタム例外
Open class StorageException:runtimeException {constructor(message:string):super(message)constructor(message:string、cause:throwable):super(message、cause)} class storagefileenotfoundexception:storeexception(メッセージ:文字列):super(message)constructor(message:string、spring:throwable):super(super、course)}構成ファイルアップロードディレクトリ
Intorg org.springframework.boot.context.properties.configurationProperties@configurationProperties( "Storage")クラスStorageProperties { / ** * Storageファイルのフォルダー場所 * / var location = "upload-dir"}スプリングブートを起動します
/*** 2018/1/9にhttp://quanke.nameによって作成されました。 */ @springbootapplication @enableconfigurationProperties(storageProperties :: class)class application {@bean internal fun init(storageservice:storageservice)= commandlinerunner {storageservice.deleteall()storageservice.init()}コンパニオンオブジェクト{@jvmstat(aguntic:array agun( 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: "$ {message}"/> </div> <div> <form method = "post" enctype = "multiPart/filed" = <ta the>アップロード:</td> <td> <入力タイプ= "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <input type = "submit" value = "upload"/> </td> </tr> </table> </form> </div> <> <> <> <ul < Th:href = "$ {file}" rel = "external nofollow" th:text = "$ {file}"/> </li> </ul> </div> </body> </html>構成ファイルapplication.yml
春:HTTP:マルチパート:Max-File-Size:128kb Max-Request-Size:128kb
Spring BootとKotlin関連のコンテンツの詳細については、「Spring Boot and Kotlin Practical Battle」に従ってください。
ソースコード:
https://github.com/quanke/spring-boot-with-kotlin-in-caction/
参照:
https://spring.io/guides/gs/uploading-files/
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。