(转)Spring Boot(十七):使用 Spring Boot 上传文件
http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring Boot 上传文件的小案例。
1、pom 包配置
我们使用 Spring Boot 版本 2.1.0、jdk 1.8、tomcat 8.0。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
引入了spring-boot-starter-thymeleaf
做页面模板引擎,写一些简单的上传示例。
2、启动类设置
@SpringBootApplication
public class FileUploadWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(FileUploadWebApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory tomcatEmbedded() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
tomcatEmbedded 这段代码是为了解决,上传文件大于10M出现连接重置的问题。此异常内容 GlobalException 也捕获不到。
详细内容参考:Tomcat large file upload connection reset
3、编写前端页面
上传页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
非常简单的一个 Post 请求,一个选择框选择文件,一个提交按钮,效果如下:
上传结果展示页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Upload Status</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
效果图如下:
4、编写上传控制类
访问 localhost 自动跳转到上传页面:
@GetMapping("/")
public String index() {
return "upload";
}
上传业务处理
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
上面代码的意思就是,通过MultipartFile
读取文件信息,如果文件为空跳转到结果页并给出提示;如果不为空读取文件流并写入到指定目录,最后将结果展示到页面。
MultipartFile
是Spring上传文件的封装类,包含了文件的二进制流和文件属性等信息,在配置文件中也可对相关属性进行配置,基本的配置信息如下:
spring.http.multipart.enabled=true
#默认支持文件上传.spring.http.multipart.file-size-threshold=0
#支持文件写入磁盘.spring.http.multipart.location=
# 上传文件的临时目录spring.http.multipart.max-file-size=1Mb
# 最大支持文件大小spring.http.multipart.max-request-size=10Mb
# 最大支持请求大小
最常用的是最后两个配置内容,限制文件上传大小,上传时超过大小会抛出异常:
更多配置信息参考这里:Common application properties
5、异常处理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
}
设置一个@ControllerAdvice
用来监控Multipart
上传的文件大小是否受限,当出现此异常时在前端页面给出提示。利用@ControllerAdvice
可以做很多东西,比如全局的统一异常处理等,感兴趣的同学可以下来了解。
6、总结
这样一个使用 Spring Boot 上传文件的简单 Demo 就完成了,感兴趣的同学可以将示例代码下载下来试试吧。
文章内容已经升级到 Spring Boot 2.x
参考:
Spring Boot file upload example
(转)Spring Boot(十七):使用 Spring Boot 上传文件的更多相关文章
- Spring Boot 静态资源映射与上传文件路由配置
默认静态资源映射目录 默认映射路径 在平常的 web 开发中,避免不了需要访问静态资源,如常规的样式,JS,图片,上传文件等;Spring Boot 默认配置对静态资源映射提供了如下路径的映射 /st ...
- Spring Boot应用上传文件时报错
问题描述 Spring Boot应用(使用默认的嵌入式Tomcat)在上传文件时,偶尔会出现上传失败的情况,后台报错日志信息如下:"The temporary upload location ...
- Spring Boot(十七):使用Spring Boot上传文件
Spring Boot(十七):使用Spring Boot上传文件 环境:Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0 一.pom包配置 <parent> ...
- springboot(十七):使用Spring Boot上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...
- spring boot(十七)上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...
- Spring Boot(十七):使用 Spring Boot 上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 Spring Boot 上传文件的小案例. 1.pom 包配置 我们使用 Spring Boot 版本 ...
- 【Spring Boot】关于上传文件例子的剖析
目录 Spring Boot 上传文件 功能实现 增加ControllerFileUploadController 增加ServiceStorageService 增加一个Thymeleaf页面 修改 ...
- spring boot下MultipartHttpServletRequest如何提高上传文件大小的默认值
前言: 上传下载功能算是一个非常常见的功能,如果使用MultipartHttpServletRequest来做上传功能. 不配置上传大小的话,默认是2M.在有些场景,这个肯定不能满足条件. 上传代码: ...
- Spring Boot 使用 ServletFileUpload上传文件失败,upload.parseRequest(request)为空
使用Apache Commons FileUpload组件上传文件时总是返回null,调试发现ServletFileUpload对象为空,在Spring Boot中有默认的文件上传组件,在使用Serv ...
随机推荐
- c#源码如何生成托管代码块
1.使用编程语言编写源码--->编程语言的编译器(面向Clr)---->生成IL代码和元数据(包含:代码中声名的类和成员 以及所引用的成员) 2.IL就被称之为托管代码,因为有Clr管理者 ...
- 【Java每日一题】20170228
20170227问题解析请点击今日问题下方的“[Java每日一题]20170228”查看(问题解析在公众号首发,公众号ID:weknow619) package Feb2017; import jav ...
- MySQL技巧(一)
NOT IN 与 IN 假设我们又一张score表如下 我们需要查询所有不是性别代号为"0"的学生数据 ); 很明显,not in 就是排除的意思. exists 与 not ex ...
- Hibernate入门(四)---------一级缓存
Hibernate一级缓存 Hibernate的一级缓存就是指Session缓存,Session缓存是一块内存空间,用来存放相互管理的java对象,在使用Hibernate查询对象的时候,首先会使用对 ...
- js 每到达5次换一行
function getYourString(s) { var res = ''; var length = s.length; for (var i = 0, j = 1; i < lengt ...
- @RequestParam加与不加的区别
最简单的两种写法,加或不加@RequestParam注解 @RequestMapping("/list") public String test(int userId) { ret ...
- 如何用ABP框架快速完成项目(3) - 为什么要使用ABP和ABP框架简介
首先先讲为什么要使用ABP? 当然是因为使用ABP可以快速完成项目啦. 时间就是金钱, 效率就是生命嘛 有了ABP, 你就节省了写如下模块的时间: CRUD数据库基本操作 校验 异常处理 日志 权 ...
- Cesium-知识点(Viewer)
Cesium之Viewer的构造(转自:https://blog.csdn.net/zhy905692718/article/details/78865107) Viewer属于Cesium的控件部分 ...
- git 入门教程之实战 git
实战 git git 是一款分布式版本控制系统,可以简单概括: 不要把鸡蛋放在一个篮子里,你的一举一动都在监视中. 实战场景 你作为某项目的其中一员或者负责人,和小伙伴们一起开发,大家既有着各自分工互 ...
- C#调用原生C++ COM对象(在C++中实现C#的接口)
为了跨平台在.net core中使用COM,不能使用Windows下的COM注册机制,但是可以直接把IUnknown指针传给C#,转换为指针,再转换为C#的接口(interface). 做了这方面的研 ...