Spring Boot 与 Kotlin 上传文件的示例代码
作者:quanke 发布时间:2022-08-24 10:24:08
标签:Spring,Boot,Kotlin,上传
如果我们做一个小型的web站,而且刚好选择的kotlin 和Spring Boot技术栈,那么上传文件的必不可少了,当然,如果你做一个中大型的web站,那建议你使用云存储,能省不少事情。
构建工程
如果对于构建工程还不是很熟悉的可以参考《我的第一个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-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"
}
创建文件上传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>()
}
}
上传文件服务的接口
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()
}
上传文件服务
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)
}
}
}
创建一个简单的 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/
来源:https://www.jianshu.com/p/d4952e71360b


猜你喜欢
- Android动画 实现开关按钮动画(属性动画之平移动画),最近做项目,根据项目需求,有一个这样的功能,实现类似开关的动画效果,经过自己琢磨
- Parallel类是对线程的一个抽象。该类位于System.Threading.Tasks名称空间中,提供了数据和任务并行性。Paralle
- isInstance和isAssignableFromobj instanceof Class判断obj是不是Class或者Class的子类
- 本文研究的主要是java中的null“类型”的相关实例,具体介绍如下。先给出一道简单的null相关的题目,引发我们对null的探讨,后面会根
- 实验目的:分别使用sqlite3工具和Android代码的方式建立SQLite数据库。在完成建立数据库的工作后,编程实现基本的数据库操作功能
- 一、获取android工程里面的各种资源的id; 1.1 string型 比如下面: << string name=”OK”&g
- J2ee 高并 * 况下 * 实例详解引言:在高并发下限制最大并发次数,在web.xml中用过滤器设置参数(最大并发数),并设置其他相关参数。
- IntelliJ IDEA中实现跟eclipse一样的outline方法,查看文件内所有已经声明的方法。mac的可以在key map 里搜索
- Comparable 简介Comparable 是排序接口。若一个类实现了Comparable接口,就意味着“该类支持排序”。
- 1、概述首先和大家一起回顾一下Java 消息服务,在我之前的博客《Java消息队列-JMS概述》中,我为大家分析了:1.消息服务:一个中间件
- 目的官方的Drools范例大都是基于纯Java项目或Maven项目,而基于Spring Boot项目的很少。本文介绍如何在Spring Bo
- 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项目是基于Springboot的,所以去网络上找了一些博客文
- minio 注册成windows 服务的工具开发using System;using System.Collections.Generic;
- 一、Struts2 * 原理:Struts2 * 的实现原理相对简单,当请求struts2的action时,Struts 2会查找配置文件,
- 后端应用经常接收各种信息参数,例如评论,回复等文本内容。除了一些场景下面,可以特定接受的富文本标签和属性之外(如:b,ul,li,h1, h
- 环境准备创建 Maven 项目创建服务器远程连接Tools------Delployment-----Browse Remote Host设
- 本文实例讲述了Android编程调用Camera和相册功能。分享给大家供大家参考,具体如下:xml:<LinearLayout xml
- 本文实例为大家分享了C#实现语音播报功能的具体代码,供大家参考,具体内容如下环境:window10vs2019 16.5.5.netfram
- 在处理模板时,可以由模板逻辑决定是否加载数据,以提高性能。在Spring Boot控制器中设置数据时,使用LazyContextVariab
- 本文实例讲述了C#基于HttpWebRequest实现发送HTTP请求的方法。分享给大家供大家参考,具体如下:调用第三方API的时候要用到H