หากเราสร้างเว็บไซต์ขนาดเล็กและเราเพียงแค่เลือกสแต็คเทคโนโลยี Kotlin และ Spring Boot การอัปโหลดไฟล์เป็นสิ่งจำเป็น แน่นอนถ้าคุณสร้างเว็บไซต์ขนาดกลางและขนาดใหญ่ขอแนะนำให้คุณใช้ที่เก็บข้อมูลบนคลาวด์ซึ่งสามารถบันทึกปัญหาได้มากมาย
บทความนี้แนะนำวิธีใช้ Kotlin และ Spring Boot เพื่ออัปโหลดไฟล์
โครงการก่อสร้าง
หากคุณไม่คุ้นเคยกับโครงการก่อสร้างคุณสามารถอ้างถึง "แอปพลิเคชัน 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 ()} "org.jetbrains.kotlin: kotlin-gradle-plugin: $ kotlin_version" classpath ("org.springframework.boot: Spring-boot-gradle-plugin: $ spring_boot_version") // Kotlin classpath ("org.jetbrains.kotlin: kotlin-noarg: $ kotlin_version") classpath ("org.jetbrains.kotlin: kotlin-allopen: $ kotlin_version")}} ใช้ปลั๊กอิน: 'kotlin'apply ปลั๊กอิน: "Kotlin-spring" // https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-pluginapply ปลั๊กอิน: 'org.springframework.boot'jar {basename =' บทที่ 11-5-6-service ' {Compile "org.jetbrains.kotlin: kotlin-stdlib-jre8: $ kotlin_version" Compile "org.springframework.boot: Spring-Boot-Starter-Web: $ spring_boot_version "org.springframework.boot: Spring-Boot-Starter-test: $ spring_boot_version" testcompile "org.jetbrains.kotlin: kotlin-test-junit: $ kotlin_version"} compilekotlin = "1.8"}สร้างตัวควบคุมการอัปโหลดไฟล์
นำเข้า Name.quanke.kotlin.chaper11_5_6.storage.storageFilenotfoundExceptionImport Name.quanke.kotlin.chaper11_5_6.storage.storageserviceimport org.springframework.beans.factory.annotation.autowiredimport org.springframework.http.httpheadersimport org.springframework.http.responseentimport org.springframework.steretype.controllerimport org.springframework.ui org.springframework.web.multipart.multipartfileimport org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsbuilderimport org.springframework.web.servlet.mvc.support java.util.stream.collectors/*** ตัวควบคุมการอัปโหลดไฟล์* สร้างโดย http://quanke.name เมื่อ 2018/1/12 */ @controlerclass fileuploadcontroller @autowiredConstructor (ส่วนตัว val storageservice: Storageservice) {@getMapping ("/") @throws (ioexception :: คลาส) Fun ListuploadedFiles (รุ่น: รุ่น): String {model.addattribute ("ไฟล์" .FrommetHodname (fileuploadController :: class.java, "ServiceFile", path.filename.toString ()) .build (). toString ()} .Collect (collector.tolist ())) return "uptoNADS FileName: String): ResponseEntity <resource> {val file = StorageService.loadAsResource (ชื่อไฟล์) ส่งคืน ResponseEntity .ok () .header (httpheaders.content_disposition, "สิ่งที่แนบมา; filename =/" "file.filename +"/") HandleFilePload (@requestparam ("ไฟล์") ไฟล์: MultipartFile, RedirectatTributes: RedirectatTributes): String {Storageservice.store (ไฟล์) Redirectattributes.addflashattribute ("ข้อความ" @ExceptionHandler (StorageFilenotFoundException :: คลาส) Fun HandlestorageFilenotFound (EXC: StorageFilenotFoundException): ResponseEntity <*> {return ResponseEntity.notFound () สร้าง <any> ()}}}}อินเทอร์เฟซสำหรับการอัปโหลดบริการไฟล์
นำเข้า org.springframework.core.io.resourceimport org.springframework.web.multipart.multipartfileimport java.nio.file.pathimport java.util.stream.streaminterface String): Path Fun LoadAsResource (ชื่อไฟล์: สตริง): Resource Fun deleteAll ()}
อัปโหลดบริการไฟล์
นำเข้า org.springframework.beans.factory.annotation.autowiredimport org.springframework.core.io.resourceimport org.springframework.core.io.urlresourceimport org.springframework.util.filesystemutilsimport org.springframework.util.stringutilsimport org.springframework.web.multipart.multipartfileimport Java.io.ioExceptionimport Java.net.malforforterforforthorleforthorleforlemport java.nio.file.pathimport Java.nio.file.Pathsimport Java.nio.file.standardcopyoptionimport java.util.stream.stream@serviceclass ระบบ {primentytlass = paths.get (properties.location)} Override Fun store (ไฟล์: MultipartFile) {val filename = stringutils.cleanpath (file.originalfilename) ลอง {ถ้า (file.isempty) {โยน storageException ("ล้มเหลวในการเก็บไฟล์ว่าง" storageException ("ไม่สามารถจัดเก็บไฟล์ด้วยเส้นทางสัมพัทธ์นอกไดเรกทอรีปัจจุบัน" + ชื่อไฟล์)} files.copy (file.inputstream, this.rootlocation.resolve (ชื่อไฟล์), StandardCopyOption.replace_existing) catch (e: ioexception) สตรีม <Ath> {ลอง {return files.walk (this.rootLocation, 1) .filter {path -> path! = this.rootlocation} .map {path -> this.rootlocation.relativize (path)}} catch (e: ioexception) พา ธ {return rootlocation.resolve (filename)} แทนที่ fun loadasresource (filename: string): ทรัพยากร {ลอง {val file = load (filename) val resource = urlresource (file.touri ()) ส่งคืน (Resource.exists () }} catch (e: malformedurlexception) {โยน storagefilenotfoundexception ("ไม่สามารถอ่านไฟล์:" + filename, e)}} แทนที่ความสนุก deleteall () {filesystemutils.deleterecursive (rootlocation.tofile () iOexception) {โยน storageException ("ไม่สามารถเริ่มต้นการจัดเก็บ", e)}}}ข้อยกเว้นที่กำหนดเอง
Open Class StorageException: RuntimeException {constructor (ข้อความ: สตริง): super (ข้อความ) constructor (ข้อความ: สตริง, สาเหตุ: throwable): super (ข้อความ, สาเหตุ)} class storagefilenotfoundexception: storageException {constructor (ข้อความ): super (ข้อความ)ไดเรกทอรีการอัพโหลดไฟล์กำหนดค่า
นำเข้า org.springframework.boot.context.properties.configurationProperties@configurationProperties ("Storage") Class StorageProperties { / ** * ตำแหน่งโฟลเดอร์สำหรับไฟล์เก็บข้อมูล * / var location = "Upload-Dir"}}}เริ่มต้นสปริงบูต
/*** สร้างโดย http://quanke.name เมื่อ 2018/1/9 */ @springbootapplication @enableConfigurationProperties (storageProperties :: คลาส) แอปพลิเคชันคลาส {@bean ความสนุกภายในเริ่มต้น (Storageservice: StorageService) = Commandlinerunner {Storageservice.deleteAll () Storageservice.init () springapplication.run (แอปพลิเคชัน :: 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 = "$ {message}"/> </div> อัปโหลด: </td> <td> <อินพุต type = "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <อินพุตประเภท = "ส่ง" value = "อัปโหลด"/> </td> </tr> Th: href = "$ {file}" rel = "ภายนอก nofollow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>แอปพลิเคชันไฟล์กำหนดค่า
ฤดูใบไม้ผลิ: HTTP: Multipart: Max-File-Size: 128KB Max-Request-Size: 128KB
สำหรับเนื้อหาที่เกี่ยวข้องกับ Spring Boot และ Kotlin เพิ่มเติมโปรดติดตาม "Spring Boot และ Kotlin Practical Battle"
ซอร์สโค้ด:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
อ้างถึง:
https://spring.io/guides/gs/uploading-files/
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น