Spring Boot(十七):使用Spring Boot上传文件
Spring Boot(十七):使用Spring Boot上传文件
环境:Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0
一、pom包配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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做页面模板引擎,写一些简单的上传示例。
二、启动类设置
@SpringBootApplication
public class FileUploadWebApplication { public static void main(String[] args) throws Exception {
SpringApplication.run(FileUploadWebApplication.class, args);
} //Tomcat large file upload connection reset
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
} }
tomcatEmbedded这段代码是为了解决,上传文件大于10M出现连接重置的问题。此异常内容GlobalException也捕获不到。
三、编写前端页面
上传页面代码:
<!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>
效果图如下:

四、编写上传控制类
访问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# 最大支持请求大小
最常用的是最后两个配置内容,限制文件上传大小,上传时超过大小会抛出异常:

五、异常处理
@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可以做很多东西,比如全局的统一异常处理等,感兴趣的同学可以下来了解。
Spring Boot(十七):使用Spring Boot上传文件的更多相关文章
- Spring Boot 静态资源映射与上传文件路由配置
默认静态资源映射目录 默认映射路径 在平常的 web 开发中,避免不了需要访问静态资源,如常规的样式,JS,图片,上传文件等;Spring Boot 默认配置对静态资源映射提供了如下路径的映射 /st ...
- Spring Boot应用上传文件时报错
问题描述 Spring Boot应用(使用默认的嵌入式Tomcat)在上传文件时,偶尔会出现上传失败的情况,后台报错日志信息如下:"The temporary upload location ...
- springboot(十七):使用Spring Boot上传文件
上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...
- (转)Spring Boot(十七):使用 Spring Boot 上传文件
http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html 上传文件是互联网中常常应用的场景之一,最典型的情 ...
- 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 ...
随机推荐
- Python random模块random/uniform/randint/choice/getrandbits/shuffle/choice/sample随机函数
1.random.random() 返回0<=n<1之间的随机实数n 2. random.uniform() 弥补了上面函数的不足,它可以设定浮点数的范围,一个是上限,一个是下限. 3. ...
- 工作流引擎--swamp
什么是工作流引擎(Workflow Engine ) 例如开发一个系统最关键的部分不是系统的界面,也不是和数据库之间的信息交换,而是如何根据业务逻辑开发出符合实际需要的程序逻辑并确保其稳定性.易维 ...
- Kotlin 范型约束
官方的示意及其简约,该说的一概没说 我在这里给大家一个完整的例子 //test.kt fun <T> cloneWhenGreater(list: List<T>, thres ...
- linux 小笔记
//强杀pid2306的进程 kill -9 2306 //查看80端口占用情况 lsof -i :80 //杀死mysql的所有进程 sudo killall mysqld //关闭占用80端口的所 ...
- teragen/terasort_简化版
1, 关闭Hadoop安全模式 进入hdfs用户 su – hdfs Cd /opt/cloudera/parcels/CDH-5.12.1-1.cdh5.12.1.p0.3/bin hdfs dfs ...
- css属性 background
background 在一个声明中设置所有的背景属性. background-attachment 设置背景图像是否固定或者随着页面的其余部分滚动. background-color 设置元素的背景颜 ...
- GeoJSON 和 TopoJSON
GeoJSON 和 TopoJSON 是符合 JSON 语法规则的两种数据格式,用于表示地理信息. 1. GeoJSON GeoJSON 是用于描述地理空间信息的数据格式.GeoJSON 不是一种新的 ...
- 20155228 2016-2017-2 《Java程序设计》第9周学习总结
20155228 2016-2017-2 <Java程序设计>第9周学习总结 教材学习内容总结 整合数据库 JDBC是用于执行SQL的解决方案,开发人员使用JDBC的标准接口,数据库厂商则 ...
- Spring源码阅读(七)
这一讲主要分析bean注册过程中各种初始化方法回调的执行逻辑(initializeBean) /** * Initialize the given bean instance, applying fa ...
- sqlyog下载
sqlyog下载(附注册码):http://www.onlinedown.net/soft/24926.htm