上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例。

1、pom包配置

我们使用Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0。

<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做页面模板引擎,写一些简单的上传示例。

2、启动类设置

@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也捕获不到。

详细内容参考: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 file upload example

示例代码-github

spring boot(十七)上传文件的更多相关文章

  1. Spring Boot (30) 上传文件

    文件上传 上传文件和下载文件是Java Web中常见的一种操作,文件上传主要是将文件通过IO流传输到服务器的某一个文件夹下. 导入依赖 在pom.xml中添加上spring-boot-starter- ...

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

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

  3. 使用Spring boot + jQuery上传文件(kotlin)

    文件上传也是常见的功能,趁着周末,用Spring boot来实现一遍. 前端部分 前端使用jQuery,这部分并不复杂,jQuery可以读取表单内的文件,这里可以通过formdata对象来组装键值对, ...

  4. Spring框架学习笔记(7)——Spring Boot 实现上传和下载

    最近忙着都没时间写博客了,做了个项目,实现了下载功能,没用到上传,写这篇文章也是顺便参考学习了如何实现上传,上传和下载做一篇笔记吧 下载 主要有下面的两种方式: 通过ResponseEntity实现 ...

  5. Spring Boot:上传文件大小超限制如何捕获 MaxUploadSizeExceededException 异常

    Spring Boot 默认上传文件大小限制是 1MB,默认单次请求大小是 10MB,超出大小会跑出 MaxUploadSizeExceededException 异常 spring.servlet. ...

  6. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  7. Android+Spring Boot 选择+上传+下载文件

    2021.02.03更新 1 概述 前端Android,上传与下载文件,使用OkHttp处理请求,后端使用Spring Boot,处理Android发送来的上传与下载请求.这个其实不难,就是特别多奇奇 ...

  8. RestTemplate OR Spring Cloud Feign 上传文件

    SpringBoot,通过RestTemplate 或者 Spring Cloud Feign,上传文件(支持多文件上传),服务端接口是MultipartFile接收. 将文件的字节流,放入ByteA ...

  9. spring boot file上传

    用Spring Boot写读取Excel文件小工具的时候遇到的一些小坑已经填平,复制即可满足普通的文件上传功能POI方面只需一个包,其他通用包工程中一般都会带TIPS:前端为了扩展我用ajax异步请求 ...

随机推荐

  1. c# 之系统环境安装

    在重装系统后,对一些原有软件进行了卸载,不知道是什么原因总是提示vs2015 需安装IE10,但是又碰到ie10的一些插件不适合此系统.网上介绍的vs修复没有任何作用 最后找到方法是:重装系统,然后不 ...

  2. 光学定位点(mark点)

     Mark点是使用机器焊接时用于定位的点.  表贴元件的pcb更需要设置Mark点,因为在大批量生产时,贴片机都是操作人员手动或者机器自动寻找Mark点进行校准.极少数不设置Mark点也可以,操作非常 ...

  3. Nand flash code

    (1)流水灯   1>我们来看原理图                                2>datasheet                             3> ...

  4. (转载)一张表搞清楚西门子S7系列标准DB块与优化DB块

    在TIA Portal中为S7-1200/S7-1500 CPU 添加一个 DB 块时,其缺省属性为优化的 DB ,优化的 DB 块与标准的 DB 块整体对比如下表所示: 项 标准 DB 优化 DB ...

  5. Tag Helpers in forms in ASP.NET Core

    Tag Helpers in ASP.NET Core Tag Helpers in forms in ASP.NET Core HTML Form element ASP.NET Core buil ...

  6. Latex: "Missing $ inserted" 解决方法

    参考: Latex报"Missing $ inserted"的解决方法 Latex: "Missing $ inserted" 解决方法 原因一:在文中出现&q ...

  7. TensorFlow 安装以及python虚拟环境

    python虚拟环境 由于TensorFlow只支持某些版本的python解释器,如Python3.6.如果其他版本用户要使用TensorFlow就必须安装受支持的python版本.为了方便在不同项目 ...

  8. Bash 和 Zsh 开启 vi-mode

    Bash 和 Zsh 开启 vi-mode bash 有两种操作模式,分别是 emacs 和 vi . 在 bash 中 set -o vi # 临时开启 vi 模式 vi ~/.bashrc # 在 ...

  9. windows 如何不显示带点的文件名、文件夹?

    这些以点开头的文件夹和文件是为了在 linux 中隐藏的.但是在 windows 中如何不显示他们? 资源管理器: CMD:

  10. JavaScript知识点整理

    1.JavaScript的定义 JavaScript是一种专门为与网页交互而设计的脚本语言.有下列三部分组成 ①ECMAScript,提供核心语言功能 ②文档对象模型(DOM),提供访问与操作网页内容 ...