最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

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

構(gòu)建工程

如果對(duì)于構(gòu)建工程還不是很熟悉的可以參考《我的第一個(gè)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"

}

啟動(dòng)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)建一個(gè)簡(jiǎn)單的 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 實(shí)戰(zhàn)》

源碼:

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

參考:

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

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

相關(guān)文章

  • 一篇文章帶你玩轉(zhuǎn)Spring bean的終極利器

    一篇文章帶你玩轉(zhuǎn)Spring bean的終極利器

    這篇文章主要給大家介紹了關(guān)于玩轉(zhuǎn)Spring bean的終極利器的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring bean具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • 在Java中以及Spring環(huán)境下操作Redis的過程

    在Java中以及Spring環(huán)境下操作Redis的過程

    文章介紹了在Java和Spring環(huán)境下操作Redis的基本方法,在Java環(huán)境下,使用Maven創(chuàng)建項(xiàng)目并導(dǎo)入Jedis依賴,通過配置端口轉(zhuǎn)發(fā)訪問Redis,文章總結(jié)了Redis的基本命令和類別,如String、list、hash、set和zset,感興趣的朋友跟隨小編一起看看吧
    2025-03-03
  • Java調(diào)取創(chuàng)藍(lán)253短信驗(yàn)證碼的實(shí)現(xiàn)代碼

    Java調(diào)取創(chuàng)藍(lán)253短信驗(yàn)證碼的實(shí)現(xiàn)代碼

    這篇文章主要介紹了Java調(diào)取創(chuàng)藍(lán)253短信驗(yàn)證碼的實(shí)現(xiàn)代碼,需要的朋友可以參考下
    2018-04-04
  • Spring Boot接口設(shè)計(jì)防篡改、防重放攻擊詳解

    Spring Boot接口設(shè)計(jì)防篡改、防重放攻擊詳解

    這篇文章主要給大家介紹了關(guān)于Spring Boot接口設(shè)計(jì)防篡改、防重放攻擊的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • SpringBoot中@Test的介紹和使用案例

    SpringBoot中@Test的介紹和使用案例

    SpringBoot提供了方便的測(cè)試功能,可以很容易地進(jìn)行單元測(cè)試和集成測(cè)試,這篇文章主要介紹了SpringBoot中@Test的介紹和使用,需要的朋友可以參考下
    2023-08-08
  • Spring中存取Bean的相關(guān)注解舉例詳解

    Spring中存取Bean的相關(guān)注解舉例詳解

    這篇文章主要給大家介紹了關(guān)于Spring中存取Bean的相關(guān)注解,在沒有使用注解獲取對(duì)象之前,我們需要在配置文件中通過添加bean來將對(duì)象存儲(chǔ)到Spring容器中,這對(duì)于我們來說是比較麻煩的,需要的朋友可以參考下
    2023-10-10
  • 2021年最新Redis面試題匯總(4)

    2021年最新Redis面試題匯總(4)

    在程序員面試過程中redis相關(guān)的知識(shí)是常被問到的話題。這篇文章主要介紹了幾道Redis面試題,整理一下分享給大家,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Mybatis優(yōu)化檢索的方法詳解

    Mybatis優(yōu)化檢索的方法詳解

    MyBatis是一款優(yōu)秀的基于Java的持久層框架,它可以將 SQL 語句和數(shù)據(jù)庫中的記錄映射成為 Java 對(duì)象,并且支持靈活的 SQL 查詢語句,在Mybatis中,可以使用動(dòng)態(tài)SQL來靈活構(gòu)造SQL語句,從而滿足各種不同的檢索需求,本文介紹Mybatis如何優(yōu)化檢索,需要的朋友可以參考下
    2024-05-05
  • SpringBoot配置動(dòng)態(tài)數(shù)據(jù)源的實(shí)戰(zhàn)詳解

    SpringBoot配置動(dòng)態(tài)數(shù)據(jù)源的實(shí)戰(zhàn)詳解

    Spring對(duì)數(shù)據(jù)源的管理類似于策略模式,不懂策略模式也沒關(guān)系,其實(shí)就是有一個(gè)全局的鍵值對(duì),類型是Map<String, DataSource>,當(dāng)JDBC操作數(shù)據(jù)庫之時(shí),會(huì)根據(jù)不同的key值選擇不同的數(shù)據(jù)源,本文介紹了SpringBoot配置動(dòng)態(tài)數(shù)據(jù)源的方法,需要的朋友可以參考下
    2024-08-08
  • Java輸出通過InetAddress獲得的IP地址數(shù)組詳細(xì)解析

    Java輸出通過InetAddress獲得的IP地址數(shù)組詳細(xì)解析

    由于byte被認(rèn)為是unsigned byte,所以最高位的1將會(huì)被解釋為符號(hào)位,另外Java中存儲(chǔ)是按照補(bǔ)碼存儲(chǔ),所以1000 0111會(huì)被認(rèn)為是補(bǔ)碼形式,轉(zhuǎn)換成原碼便是1111 0001,轉(zhuǎn)換成十進(jìn)制數(shù)便是-121
    2013-09-09

最新評(píng)論

汉寿县| 财经| 唐山市| 孝昌县| 长乐市| 高淳县| 上饶市| 沁源县| 鹤峰县| 双牌县| 石屏县| 广东省| 固镇县| 遂川县| 鲁甸县| 聂拉木县| 临湘市| 安平县| 和平区| 麻江县| 靖边县| 防城港市| 灌云县| 延安市| 巫山县| 阿克苏市| 深水埗区| 中江县| 中宁县| 常山县| 册亨县| 池州市| 枣庄市| 梁平县| 丰镇市| 木里| 张家界市| 武平县| 左云县| 凤台县| 吴忠市|