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 ...
随机推荐
- 亲爱的,我是一条Linux运维技术学习路径呀。
根据我的经验,人在年轻时,最头疼的一件事就是决定自己这一生要做什么.在这方面,我倒没有什么具体的建议:干什么都可以,但最好不要写小说,这是和我抢饭碗.总而言之,干什么都是好的:但要干出个样子来,这才是 ...
- Apache服务安全加固
一.账号设置 以专门的用户帐号和用户组运行 Apache 服务. 根据需要,为 Apache 服务创建用户及用户组.如果没有设置用户和组,则新建用户,并在 Apache 配置文件中进行指定. 创建 A ...
- Hybrid设计--账号体系的建设
前后端分离:开发效率高,没有SEO 现在是重客户端设计:交互和业务逻辑是前端来写,适合做前后端分离.对前端更友好,提高了效率. 传统模式开发:整个业务逻辑是server端写,不适合做前后端分离.ser ...
- iOS UI进阶-1.1 Quartz2D 图片水印/裁剪/截图
图片水印 UIImage+MJ.h #import <UIKit/UIKit.h> @interface UIImage (MJ) /** * 打水印 * * @param bg 背景图片 ...
- 关于随机数、方法重载和System.out.println()的认识
(1)使用纯随机数发生器编写一个指定数目内数字的程序(类真随机数) 源代码: package Demo1; public class trueRandom { long Multiplier = 45 ...
- mysql----------局域网数据库:如何让navicat链接局域网其他的数据库。
1.找到被链接的数据库,打开以后有一个自带的mysql数据库,打开以后下面有一个user表,把里面的第一条数据的第一个字段改成% 百分号,然后保存,重启数据库,搞定 2.如果是linux下的话,记得把 ...
- 解决session只能被一个浏览器访问的问题
做购物车的时候,我们都知道购买的东西会保存到session中,但是光这样简单的保存起来就会带来一个问题,只能呢被同一个浏览器访问到,如果用户使用不同的浏览器进行访问网页的话肯定是会出问题的.下面就来针 ...
- sql 存储过程命名规范
规范的命名可以提高开发和维护的效率,如果你正在创建一个新的存储过程,请参考如下的命名规范. 句法: 存储过程的命名有这个的语法:[proc] [MainTableName] By [FieldName ...
- mysql 5.6 分区与不分区的区别
mysql> CREATE TABLE t1 ( id INT, date DATETIME DEFAULT CURRENT_TIMESTAMP) ENGINE=Innodb; Query OK ...
- python中impyla包报'TSocket' object has no attribute 'isOpen'错误
经搜索得知,是thrift-sasl的版本太高了(0.3.0),故将thrift-sasl的版本降级到0.2.1 pip install thrift-sasl==0.2.1 经测试impyla 可以 ...