Sample Code for uploading files using Spring Boot and Kotlin, and kotlin sample code

Source: Internet
Author: User

Sample Code for uploading files using Spring Boot and Kotlin, and kotlin sample code

If we make a small web site, and we just choose the kotlin and Spring Boot technology stacks, then it is essential to upload files. Of course, if you are building a medium or large web site, we recommend that you use cloud storage to save a lot of trouble.

This article introduces how to use kotlin and Spring Boot to upload files.

Construction Project

If you are not familiar with the construction project, refer to my first Kotlin application.

Complete build. gradle File

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 integrates SpringBoot's default no-argument constructor. By default, 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 "}

Create File Upload 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. springframewo Rk. 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/*** File Upload controller * Created by http://quanke.name on 2018/1/12. * // @ Controllerc Lass FileUploadController @ Autowiredconstructor (private val storageService: StorageService) {@ GetMapping ("/") @ Throws (IOException: class) fun listUploadedFiles (model: Model): String {model. addattriice ("files", storageService. loadAll (). map {path-> MvcUriComponentsBuilder. fromMethodName (FileUploadController: class. java, "serveFile", path. fileName. toString ()). build (). toString ()}. collect (Co Llectors. 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 (@ RequestPar Am ("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> ()}}

Upload File Service Interface

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

File Upload Service

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

Custom exception

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

Configuration File Upload directory

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

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

Create a simple html template src/main/resources/templates/uploadForm.html

Configuration file application. yml

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

For more information about Spring Boot and kotlin, please pay attention to Spring Boot and kotlin practices.

Source code:

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

Refer:

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

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.