国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

Spring Boot 與 Kotlin 上傳文件的示例代碼

2024-07-13 10:17:03
字體:
來源:轉載
供稿:網友

如果我們做一個小型的web站,而且剛好選擇的kotlin 和Spring Boot技術棧,那么上傳文件的必不可少了,當然,如果你做一個中大型的web站,那建議你使用云存儲,能省不少事情。

這篇文章就介紹怎么使用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()  }  dependencies {    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"    classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version")//    Kotlin整合SpringBoot的默認無參構造函數,默認把所有的類設置open類插件    classpath("org.jetbrains.kotlin:kotlin-noarg:$kotlin_version")    classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlin_version")      }}apply plugin: 'kotlin'apply plugin: "kotlin-spring" // See https://kotlinlang.org/docs/reference/compiler-plugins.html#kotlin-spring-compiler-pluginapply plugin: 'org.springframework.boot'jar {  baseName = 'chapter11-5-6-service'  version = '0.1.0'}repositories {  mavenCentral()}dependencies {  compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"  compile "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-boot-starter-test:$spring_boot_version"  testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"}compileKotlin {  kotlinOptions.jvmTarget = "1.8"}compileTestKotlin {  kotlinOptions.jvmTarget = "1.8"}

創建文件上傳controller

import name.quanke.kotlin.chaper11_5_6.storage.StorageFileNotFoundExceptionimport name.quanke.kotlin.chaper11_5_6.storage.StorageServiceimport org.springframework.beans.factory.annotation.Autowiredimport org.springframework.core.io.Resourceimport org.springframework.http.HttpHeadersimport org.springframework.http.ResponseEntityimport org.springframework.stereotype.Controllerimport org.springframework.ui.Modelimport org.springframework.web.bind.annotation.*import org.springframework.web.multipart.MultipartFileimport org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilderimport org.springframework.web.servlet.mvc.support.RedirectAttributesimport java.io.IOExceptionimport java.util.stream.Collectors/** * 文件上傳控制器 * Created by http://quanke.name on 2018/1/12. */@Controllerclass FileUploadController @Autowiredconstructor(private val storageService: StorageService) {  @GetMapping("/")  @Throws(IOException::class)  fun listUploadedFiles(model: Model): String {    model.addAttribute("files", storageService        .loadAll()        .map { path ->          MvcUriComponentsBuilder              .fromMethodName(FileUploadController::class.java, "serveFile", path.fileName.toString())              .build().toString()        }        .collect(Collectors.toList()))    return "uploadForm"  }  @GetMapping("/files/{filename:.+}")  @ResponseBody  fun serveFile(@PathVariable filename: String): ResponseEntity<Resource> {    val file = storageService.loadAsResource(filename)    return ResponseEntity        .ok()        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=/"" + file.filename + "/"")        .body(file)  }  @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): ResponseEntity<*> {    return ResponseEntity.notFound().build<Any>()  }}

上傳文件服務的接口

import org.springframework.core.io.Resourceimport org.springframework.web.multipart.MultipartFileimport java.nio.file.Pathimport java.util.stream.Streaminterface StorageService {  fun init()  fun store(file: MultipartFile)  fun loadAll(): Stream<Path>  fun load(filename: String): Path  fun loadAsResource(filename: String): Resource  fun deleteAll()}

上傳文件服務

import org.springframework.beans.factory.annotation.Autowiredimport org.springframework.core.io.Resourceimport org.springframework.core.io.UrlResourceimport org.springframework.stereotype.Serviceimport org.springframework.util.FileSystemUtilsimport org.springframework.util.StringUtilsimport org.springframework.web.multipart.MultipartFileimport java.io.IOExceptionimport java.net.MalformedURLExceptionimport java.nio.file.Filesimport java.nio.file.Pathimport java.nio.file.Pathsimport java.nio.file.StandardCopyOptionimport java.util.stream.Stream@Serviceclass FileSystemStorageService @Autowiredconstructor(properties: StorageProperties) : StorageService {  private val rootLocation: Path  init {    this.rootLocation = Paths.get(properties.location)  }  override fun store(file: MultipartFile) {    val filename = StringUtils.cleanPath(file.originalFilename)    try {      if (file.isEmpty) {        throw StorageException("Failed to store empty file " + filename)      }      if (filename.contains("..")) {        // This is a security check        throw StorageException(            "Cannot store file with relative path outside current directory " + filename)      }      Files.copy(file.inputStream, this.rootLocation.resolve(filename),          StandardCopyOption.REPLACE_EXISTING)    } catch (e: IOException) {      throw StorageException("Failed to store file " + filename, e)    }  }  override fun loadAll(): Stream<Path> {    try {      return Files.walk(this.rootLocation, 1)          .filter { path -> path != this.rootLocation }          .map { path -> this.rootLocation.relativize(path) }    } catch (e: IOException) {      throw StorageException("Failed to read stored files", e)    }  }  override fun load(filename: String): Path {    return rootLocation.resolve(filename)  }  override fun loadAsResource(filename: 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)    }  }}

自定義異常

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)}

配置文件上傳目錄

import org.springframework.boot.context.properties.ConfigurationProperties@ConfigurationProperties("storage")class StorageProperties {  /**   * Folder location for storing files   */  var location = "upload-dir"}

啟動Spring Boot

/** * Created by http://quanke.name on 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)    }  }}

創建一個簡單的 html模板 src/main/resources/templates/uploadForm.html

<html xmlns:th="http://www.thymeleaf.org"><body><div th:if="${message}">  <h2 th:text="${message}"/></div><div>  <form method="POST" enctype="multipart/form-data" action="/">    <table>      <tr>        <td>File to upload:</td>        <td><input type="file" name="file"/></td>      </tr>      <tr>        <td></td>        <td><input type="submit" value="Upload"/></td>      </tr>    </table>  </form></div><div>  <ul>    <li th:each="file : ${files}">      <a th:href="${file}" rel="external nofollow" th:text="${file}"/>    </li>  </ul></div></body></html>

配置文件 application.yml

spring: http:  multipart:   max-file-size: 128KB   max-request-size: 128KB

更多Spring Boot 和 kotlin相關內容,歡迎關注 《Spring Boot 與 kotlin 實戰》

源碼:

https://github.com/quanke/spring-boot-with-kotlin-in-action/

參考:

https://spring.io/guides/gs/uploading-files/

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 松滋市| 英德市| 广水市| 达孜县| 百色市| 财经| 凉城县| 习水县| 兴和县| 兴业县| 康乐县| 五大连池市| 温泉县| 闸北区| 娱乐| 皮山县| 天水市| 许昌县| 汪清县| 巴马| 贵阳市| 靖江市| 刚察县| 宜宾市| 高清| 乾安县| 左贡县| 东台市| 衡东县| 邻水| 兴安县| 江源县| 湟中县| 科技| 合山市| 昌平区| 新巴尔虎左旗| 乡宁县| 当涂县| 乌兰县| 晋宁县|