上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个 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

示例代码-github

示例代码-码云

参考:

Spring Boot file upload example

文章来源于;https://www.cnblogs.com/ityouknow/p/8298344.html

Spring Boot(十七):使用 Spring Boot 上传文件的更多相关文章

  1. Spring Boot 静态资源映射与上传文件路由配置

    默认静态资源映射目录 默认映射路径 在平常的 web 开发中,避免不了需要访问静态资源,如常规的样式,JS,图片,上传文件等;Spring Boot 默认配置对静态资源映射提供了如下路径的映射 /st ...

  2. Spring Boot应用上传文件时报错

    问题描述 Spring Boot应用(使用默认的嵌入式Tomcat)在上传文件时,偶尔会出现上传失败的情况,后台报错日志信息如下:"The temporary upload location ...

  3. Spring Boot(十七):使用Spring Boot上传文件

    Spring Boot(十七):使用Spring Boot上传文件 环境:Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0 一.pom包配置 <parent> ...

  4. springboot(十七):使用Spring Boot上传文件

    上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...

  5. (转)Spring Boot(十七):使用 Spring Boot 上传文件

    http://www.ityouknow.com/springboot/2018/01/12/spring-boot-upload-file.html 上传文件是互联网中常常应用的场景之一,最典型的情 ...

  6. spring boot(十七)上传文件

    上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例. 1.pom包配置 我们使用Spring Boot最新版本1.5.9. ...

  7. 【Spring Boot】关于上传文件例子的剖析

    目录 Spring Boot 上传文件 功能实现 增加ControllerFileUploadController 增加ServiceStorageService 增加一个Thymeleaf页面 修改 ...

  8. spring boot下MultipartHttpServletRequest如何提高上传文件大小的默认值

    前言: 上传下载功能算是一个非常常见的功能,如果使用MultipartHttpServletRequest来做上传功能. 不配置上传大小的话,默认是2M.在有些场景,这个肯定不能满足条件. 上传代码: ...

  9. Spring Boot 使用 ServletFileUpload上传文件失败,upload.parseRequest(request)为空

    使用Apache Commons FileUpload组件上传文件时总是返回null,调试发现ServletFileUpload对象为空,在Spring Boot中有默认的文件上传组件,在使用Serv ...

随机推荐

  1. Windows系统下如何卸载干净mysql

    一.在控制面板中卸载mysql软件 二.卸载过后删除C:\Program Files (x86)\MySQL该目录下剩余了所有文件,把mysql文件夹也删了 三.windows+R运行“regedit ...

  2. 记二进制搭建k8s集群完成后,部署时容器一直在创建中的问题

    gcr.io/google_containers/pause-amd64:3.0这个容器镜像国内不能下载容器一直创建中是这个原因 在kubelet.service中配置 systemctl daemo ...

  3. Matlab复习

    Matlab是刚好两年前(大三)接触的,那时一些课程(遥感图像处理.计量地理学......)要涉及简单的数学建模的问题.Matlab在那些资深的开发者看来可能是一门有点边缘化的东西,虽然也能做开发,能 ...

  4. css设置元素垂直居中的几个方法

    最近有人问我怎么设置元素垂直居中?我....(这么基础的东西都不会?我有点说不出话来),  不过还是耐心的教了他几个方法,好吧教完他们,顺便把这些方法整理一下 第一种:通过设置成为表格元素的方式来实现 ...

  5. react -搭建服务-2

    export const DEFAULT_TITLE = "你好"; // export const PRODUCT_SERVER_URL = "http://10.10 ...

  6. jquery delegate()方法 语法

    jquery delegate()方法 语法 作用:delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数.使用 delegate( ...

  7. css之页面透明

    能使元素变的透明的方法有: 1.Opacity 2.RGBA opacity会使后代元素都透明,而RGBA不会!

  8. Codeforces 1213G Path Queries

    cf题面 中文题面 给一棵无根树,每条边有边权.然后q个询问,每次询问给个w,求树上有多少对点之间的路径上的最大值小于等于w. 解题思路 离线.先把所有边按照边长升序排序,再把所有询问按照w升序排序. ...

  9. CodeForces451E Devu and Flowers

    题目链接 问题分析 没有想到母函数的做法-- 其实直接看题思路挺简单的.发现如果每种花都有无限多的话,问题变得十分简单,答案就是\(s+n-1\choose n - 1\).然后发现\(n\)只有\( ...

  10. 前端23种js设计模式中参见的7种设计模式的学习

    创建型设计模式是一类处理对象创建的设计模式,通过某种方式控制对象的创建来避免基本对象创建时可能导致设计上的问题或增加设计上的复杂度. 1)工厂模式 class Product { constructo ...