إذا قمنا بإنشاء موقع ويب صغير وقمنا فقط باختيار مكدسات Kotlin و Spring Boot Technology ، فإن تحميل الملفات أمر ضروري. بالطبع ، إذا قمت بإنشاء موقع ويب متوسط وكبير ، فمن المستحسن أن تستخدم التخزين السحابي ، مما قد يوفر الكثير من المتاعب.
تقدم هذه المقالة كيفية استخدام 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 classpath ("org.springframework.boot: spring-boot-plugin: $ spring_boot_version") classpath ("org.jetbrains.kotlin: kotlin-allopen: $ kotlin_version")}} تطبيق البرنامج المساعد: 'kotlin'apply plugin: "kotlin-spring" // see https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin 'org.springframework.boot'jar {basename =' appack11-5-6-service 'version =' 0.1.0 '} المستودعات {mavencentral ()} تبعيات {compile "org.jetbrains.kotlin "org.springframework.boot: spring-boot-starter-web: $ spring_boot_version" compile "org.springframework.boot: spring-boot-starter-thymeleaf: $ spring_boot_version" testcompile "org.jetbrains.kotlin: kotlin-test-junit: $ kotlin_version"} compilekotlin {kotlinoptions.jvmtarget = "1.8"} compiletestkotlin {kotlinoptions.jvmtarget = 1.8 "}}إنشاء وحدة تحكم تحميل الملف
استيراد name.quanke.kotlin.chaper11_5_6.storage.storagefilenotfoundExceptionImport name.quanke.kotlin.chaper11_5_6.storage.storageserviceimport org.springframework.beans.factory.antower org.springframework.http.httpheadersimport org.springframework.http.responseentityimport org.springframework.steretype.controllerimport org.springframework.ui.modelimport org.springframework.bind.ant. 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. */ @controlRclass fileUploAdControllerRollerAuderConstructor (Private Val Storageservice: Storageservice) {getMapping ("/") therws (ioException :: class) listuploadedfiles (model: model): string {model.addattribute ("files" ، storageservice. mvcuricomponentsbuilder .frommethodName (fileUploadController :: class.java ، "servile" ، path.filename.toString ()) .build (). responsebody متعة servile (اسم ملف pathvariable: سلسلة): استجابة <rofression> {val file = storageservice.loadasresource (fileName) response responseentity .ok () .header (httpheaders.content_disposition ، "fileName =/" + file.filename + "/"). GEALLEFILEUPLOAD (REQUESTPARAM ("file") الملف: multipartfile ، redirectattributes: redirectattributes): String {Storageservice.store (file) redirectattributes.addflashattribute ("message" ، "لقد تم تحميلك بنجاح" + file.originalfilename + "!" exceptionHandler (storagefilenotfoundException :: class) متعة handlestoragefilenotfound (exc: storagefilenotfoundException): الاستجابة <*> {return reponseentity.notfound (). Build <ho> ()}}واجهة لتحميل خدمة الملفات
استيراد org.springframework.core.io.resourceimport org.springframework.web.multipart.multipartfileimport java.nio.file.pathimport java.util.stream.stream Fun LoadAsresource (اسم الملف: سلسلة): Resource Fun Deleteall ()}
تحميل خدمة الملف
استيراد org.springframework.beans.factory.annotation. org.springframework.util.stringutilsimport org.springframework.web.multipart.multipartfileimport java.nio.file.standardCopyOptionImport java.util.stream.stream@serviceClass filesystemstorageservice {val filename = stringutils.cleanpath (file.originalfilename) حاول {if (file.isempty) {throw storageException ( files.copy (file.inputStream ، this.rootlocation.resolve (اسم الملف) ، standardCopyOption.replace_existing)} catch (e: ioException) {throw storageExcept path -> path! = this.rootlocation} .map {path -> this.rootlocation.relativize (path)}} catch (e: ioException) {throw storageException ( Resource {try {val file = load (filename) val Resource = urlResource (file.touri ()) return if (resource.exists () || resource.isreadable) {resource} else {thow storagefilenotfoundException ("لا يمكن قراءة الملف:" + filename)}}}} + اسم الملف ، e)}} override fun deleteall () {fileystemUtils.deLeterCursivily (rootlocation.tofile ())} تجاوز المرح init () {tryاستثناءات مخصصة
فتح فئة storageException: RunTimeException {مُنشئ (الرسالة: السلسلة): مُنشئ Super (رسالة) (الرسالة: سلسلة ، السبب: قابلة للتسمية): Super (رسالة ، سبب)} Class StorageFilenotFoundFoundexception: STOGEREXCESTIONدليل تحميل ملف التكوين
استيراد org.springframework.boot.context.properties.ConfigurationProperties@ConfigurationProperties ("Storage") Class StorageProperties { / ** * folder for files storage * / var location = "Upload-dir"}ابدأ الحذاء الربيعي
/*** تم إنشاؤه بواسطة http://quanke.name في 2018/1/9. */ @springbootapplication @enableConfigurationProperties (StorageProperties :: class) تطبيق الفئة {bean internal fun init (storageservice: storageservice) = companslinerunner صفيف <string>) {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}"/> </viv> <div> التحميل: </td> <td> <td type = "file" name = "file"/> </td> </td> <td> <td> </td> <td> <type type = "إرسال" value = "upload"/> </td> </tr> Th: href = "$ {file}" rel = "nofollow external" th: text = "$ {file}"/> </li> </ul> </viv> </body> </html>ملف التكوين Application.yml
الربيع: http: multipart: max-file-size: 128kb max-request-size: 128kb
لمزيد من المحتوى الربيعي ومحتوى Kotlin ، يرجى متابعة "Spring Boot و Kotlin المعركة العملية"
رمز المصدر:
https://github.com/quanke/spring-boot-with-kotlin-in-action/
الرجوع إلى:
https://spring.io/guides/gs/uploading-files/
ما سبق هو كل محتوى هذه المقالة. آمل أن يكون ذلك مفيدًا لتعلم الجميع وآمل أن يدعم الجميع wulin.com أكثر.