Jika kami membangun situs web kecil dan kami hanya memilih tumpukan teknologi boot Kotlin dan Spring, maka mengunggah file sangat penting. Tentu saja, jika Anda membangun situs web sedang dan besar, disarankan agar Anda menggunakan penyimpanan cloud, yang dapat menghemat banyak masalah.
Artikel ini memperkenalkan cara menggunakan Kotlin dan Spring Boot untuk mengunggah file
Proyek Konstruksi
Jika Anda tidak terlalu terbiasa dengan proyek konstruksi, Anda dapat merujuk ke "aplikasi Kotlin pertama saya"
Lengkap file build.gradle
grup 'name.quanke.kotlin'version' 1.0-snapshot'buildscript {ext.kotlin_version = '1.2.10' ext.spring_boot_version = '1.5.4.release' Repositori {Mavencentral ()} Ketergantungan {classpath "org.jetbrains (mavencentral ()} Dependensi {classpath" org.jetbrains. classpath ("org.springframework.boot: spring-boot-gradle-plugin: $ spring_boot_version") // Kotlin mengintegrasikan konstruktor tanpa parameter default springboot, dan mengatur semua kelas untuk membuka plugin kelas classpath ("org.jetbrains.kotlin: Kotlin-noargin: $") classpath ("org.jetbrains.kotlin: Kotlin-Allopen: $ Kotlin_version")}} Terapkan plugin: 'Kotlin'Apply Plugin: "Kotlin-Spring" // Lihat https://kotlinlang.org/docs/reference/compiler-pluler-lugin-luginer Plugin: 'org.springframework.boot'jar {baseName =' bab11-5-6-service 'versi =' 0.1.0 '} repositori {mavencentral ()} dependensi {compile "org.jetbrains.kotlin: Kotlin-stdlib-Jre8: $ Kotlin" Kotlinlin: $ Kotlin-stdlib-Jre8: $ Kotlin " "org.springframework.boot: spring-boot-starter-web: $ spring_boot_version" compile "org.springframework.boot: spring-boot-starter-thymeleaf: $ spring_boot_version" testCompile "org.springframework.boot: spring-boots-starpile" org.springframework.boot: Spring-boots-starpile "org.springframework "org.jetBrains.kotlin: Kotlin-Test-Junit: $ Kotlin_Version"} compilekotlin {Kotlinoptions.jvmTarget = "1.8"} CompileTestKotlin {Kotlinoptions.jvmTarget = "1.8"}Buat pengontrol unggahan file
Impor name.quanke.kotlin.chaper11_5_6.storage.storagefilenotfoundExceptionImport name.QUANKE.KOTLIN.CHAPER11_5_6.Storage.StorageServiceImport org.springframework.beans.factory.annotation.AutowImport org.sprramework.beans.factory.annotation.AutowImport org.spramework.beans.factory.annotation.AutowIpport.sprramework.bean.factory.annotation.AutowCorCport org.springframework.http.httpheadersImport org.springframework.http.responseentityImport org.springframework.steretype.controllerimport org.springframework. org.springframework.web.multipart.multipartfileImport org.springframework.web.servlet.mvc.method.annotation.mvcuricomponentsBuilderImport org.spramework.web.servlet.mvc.support.sepport.sepport.sepport.sepport. java.util.stream.collectors/*** Pengontrol unggahan file* dibuat oleh http://quanke.name pada 2018/1/12. */ @ControllerClass FileUploadController @AutowiredConstructor (Private Val StorageService: StorageService) {@getMapping ("/") @throws (ioException :: class) Fun ListupLoadedFiles (Model: Model): String {Model.Addattribute ("File", StorageRerve. Mvcuricomponentsbuilder .frommethodname (FileUploadController :: class.java, "serveFile", path.filename.tostring ()) .build (). @ @ @ @{ @{} @ @{ @{ @{Collectors.tolist (). @ResponseBody Fun ServeFile (@PathVariable FileName: String): ResponseEntity <Ranggern> {val file = StorageService.LoadAsResource (fileName) ReturnEntity .ok () .Header (httpheaders.content_disposition, "lampiran; fileName =/" " + FILE.FiEDERS.CONTENT_DISPOSION," lampiran; fileName =/"" + FILE.FILE. " @PostMapping ("/") Fun handleFileUpload (@RequestParam ("File") File: MultipartFile, RedirectAttributes: RedirectAttributes): String {StorageService.Store (file) redirectattributes.addflashattribute ("Message", "Anda berhasil mengunggah" dengan sukses. " } @ExceptionHandler (StorageFileNotFoundException :: class) Fun handlestorageFileNoTfound (exc: storageFileNotFoundException): responEntity <*> {return responentity.notfound ().Antarmuka untuk mengunggah layanan file
impor org.springframework.core.io.resourceImport org.springframework.web.multipart.multipartfileImport java.nio.file.pathimport Java.util. Fun LoadAsResource (nama file: string): sumber daya fun deleteall ()}
Unggah Layanan File
Impor org.springframework.beans.factory.annotation.AutowiredImport org.springframework.core.io.ResourceImport org.springframework.core.serviceImport org.springframework.stereotype.serviceImport org.springframework.stereotype.serviceImport org.springframework.stereotype.serviceImport org.springframework.stereotype.serviceImport org.springframework.stereotype.serviceImport org.springframework.stereotype.serviceImport org.springframework.stereotype.serviceMport org org.springframework.util.stringutilsimport org.springframework.web.multipart.multipartfileImport java.io.ioExceptionImport java.net.malformedlexceptionImport java.nio.file.file.pilesport Java. java.nio.file.StandardCopyOptionImport java.util.stream.stream@serviceclass FilesystemStorageService @AutowiredConstructor (Properties: StorageProperties): StorageService {Private Val RootLocation: Path init {this.rootlocies = PATH. PATHGET (PATT. {val filename = stringutils.cleanpath (file.originalfileName) coba {if (file.isempty) {throw storeageException ("Gagal menyimpan file kosong" + fileName)} if (filename.contains ("..") {// Ini adalah are store nexcepore (".." File.copy (file.inputStream, this.rootlocation.resolve (fileName), StandardCopyOption.Replace_existing)} catch (e: ioException) {throw storeageException ("Gagal file" + FileName, e)}} overlide loadall (): stream <) {filename, e)}} override loadall (): stream <) {filename, e)}} overlide loadall. .filter {path -> path! = this.rootlocation} .map {path -> this.rootlocation.relativize (path)}} catch (e: ioException) {throw storeageException ("gagal membaca file yang tersimpan", e)}} override Fun Load (fileName: string): Path overlocation. LoadAsResource (fileName: string): sumber daya {coba {val file = load (nama file) val resource = urlResource (file.touri ()) return if (resource.exists () || resource.isreadable) {sumber daya} {throw storAgeFileNotFoundException ("tidak dapat dibaca (" tidak dapat dibaca ("tidak dapat dibaca (" 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 ("tidak dapat menginisialisasi penyimpanan", e)}}}Pengecualian khusus
open class StorageException : RuntimeException { constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause)}class StorageFileNotFoundException : StorageException { constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause)}Direktori Unggah File Konfigurasi
impor org.springframework.boot.context.properties.configurationproperties@configurationproperties ("Storage") Class StorageProPerties { / ** * Lokasi folder untuk file penyimpanan * / var location = "unggah-dir"}}Mulai Spring Boot
/*** dibuat oleh http://quanke.name pada 2018/1/9. */ @SpringbootApplication @enableConfigurationProperties (StorageProPerties :: class) Aplikasi kelas {@bean internal fun init (StorageService: StorageService) = commandlinunner {storageService.deleteal () classion: classion: classion () @company () @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ {SpringApplication.run (application :: class.java, *args)}}}Buat templat HTML sederhana SRC/Main/Resources/Templates/UploadForm.html
<html xmlns: th = "http://www.thymeleaf.org"> <body> <v: if = "$ {message}"> <h2 th: text = "$ {pesan}"/> </div> <div> <bentuk metode = "post" owctype = "multipart/form Unggah: </td> <td> <input type = "file" name = "file"/> </td> </tr> <tr> <td> </td> <td> <input type = "kirim" value = "unggah"/> </td </tr> </table> </formrom> </div> </{{{{{a. TH: href = "$ {file}" rel = "eksternal nofollow" th: text = "$ {file}"/> </li> </ul> </div> </body> </html>Configuration File Application.yml
Spring: HTTP: Multipart: Max-File-Ukuran: 128KB Max-Request-Size: 128KB
Untuk lebih banyak konten terkait Spring Boot dan Kotlin, silakan ikuti "Spring Boot dan Kotlin Practical Battle"
Kode Sumber:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
Lihat:
https://spring.io/guides/gs/uploading-files/
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.