欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2018年01月22日 08:36:49   作者:quanke  
這篇文章主要介紹了Spring Boot 與 Kotlin 上傳文件的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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

這篇文章就介紹怎么使用kotlin 和Spring Boot上傳文件

構(gòu)建工程

如果對于構(gòu)建工程還不是很熟悉的可以參考《我的第一個Kotlin應(yīng)用

完整 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的默認(rèn)無參構(gòu)造函數(shù),默認(rèn)把所有的類設(shè)置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-plugin
apply 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"
}

創(chuàng)建文件上傳controller

import name.quanke.kotlin.chaper11_5_6.storage.StorageFileNotFoundException
import name.quanke.kotlin.chaper11_5_6.storage.StorageService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.Resource
import org.springframework.http.HttpHeaders
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder
import org.springframework.web.servlet.mvc.support.RedirectAttributes

import java.io.IOException
import java.util.stream.Collectors


/**
 * 文件上傳控制器
 * Created by http://quanke.name on 2018/1/12.
 */

@Controller
class FileUploadController @Autowired
constructor(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>()
  }

}

上傳文件服務(wù)的接口

import org.springframework.core.io.Resource
import org.springframework.web.multipart.MultipartFile

import java.nio.file.Path
import java.util.stream.Stream

interface StorageService {

  fun init()

  fun store(file: MultipartFile)

  fun loadAll(): Stream<Path>

  fun load(filename: String): Path

  fun loadAsResource(filename: String): Resource

  fun deleteAll()

}

上傳文件服務(wù)

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.io.Resource
import org.springframework.core.io.UrlResource
import org.springframework.stereotype.Service
import org.springframework.util.FileSystemUtils
import org.springframework.util.StringUtils
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.net.MalformedURLException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption
import java.util.stream.Stream

@Service
class FileSystemStorageService @Autowired
constructor(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)
    }
  }
}

創(chuàng)建一個簡單的 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相關(guān)內(nèi)容,歡迎關(guān)注 《Spring Boot 與 kotlin 實戰(zhàn)》

源碼:

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

參考:

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 基于logback實現(xiàn)純java版本的SDK組件

    基于logback實現(xiàn)純java版本的SDK組件

    這篇文章主要介紹了基于logback實現(xiàn)純java版本的SDK組件,在項目開發(fā)過程中通常會使用logback作為日志記錄的依賴工具,使用方式是引入logback相關(guān)jar包,然后配置logback.xml配置文件的方式來實現(xiàn),需要的朋友可以參考下
    2023-11-11
  • java 將字符串追加到文件已有內(nèi)容后面的操作

    java 將字符串追加到文件已有內(nèi)容后面的操作

    這篇文章主要介紹了java 將字符串追加到文件已有內(nèi)容后面的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • Spring Boot CLI使用教程

    Spring Boot CLI使用教程

    本篇文章主要介紹了Spring Boot CLI使用教程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • SpringMVC異常處理器編寫及配置

    SpringMVC異常處理器編寫及配置

    這篇文章主要介紹了SpringMVC異常處理器編寫及配置,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • 關(guān)于Feign調(diào)用服務(wù)Headers傳參問題

    關(guān)于Feign調(diào)用服務(wù)Headers傳參問題

    這篇文章主要介紹了關(guān)于Feign調(diào)用服務(wù)Headers傳參問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Spring循環(huán)依賴正確性及Bean注入的順序關(guān)系詳解

    Spring循環(huán)依賴正確性及Bean注入的順序關(guān)系詳解

    這篇文章主要給大家介紹了關(guān)于Spring循環(huán)依賴的正確性,以及Bean注入的順序關(guān)系的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2018-01-01
  • 避免Java中的內(nèi)存泄漏的三種方法

    避免Java中的內(nèi)存泄漏的三種方法

    在Java開發(fā)中,內(nèi)存泄漏(Memory Leak)是一個常見但令人頭疼的問題,本文將深入探討什么是內(nèi)存泄漏、常見的泄漏原因、如何識別和避免內(nèi)存泄漏,以及通過代碼示例展示如何優(yōu)化Java程序以減少內(nèi)存泄漏的發(fā)生,需要的朋友可以參考下
    2024-07-07
  • Java實現(xiàn)連接kubernates集群的兩種方式詳解

    Java實現(xiàn)連接kubernates集群的兩種方式詳解

    這篇文章主要為大家詳細介紹了Java實現(xiàn)連接kubernates集群的兩種方式,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • Spring?Boot如何實現(xiàn)統(tǒng)一數(shù)據(jù)返回

    Spring?Boot如何實現(xiàn)統(tǒng)一數(shù)據(jù)返回

    這篇文章主要介紹了Spring?Boot如何實現(xiàn)統(tǒng)一數(shù)據(jù)返回,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • 快速入手IntelliJ IDEA基本配置

    快速入手IntelliJ IDEA基本配置

    IntelliJ IDEA是java編程語言開發(fā)的集成環(huán)境,本篇主要介紹了對它的安裝、配置maven倉庫、調(diào)試方法、常用的插件推薦、快捷鍵大全與常用快捷鍵說明,感興趣的朋友一起看看吧
    2021-10-10

最新評論