使用 Spring Boot 和 Thymeleaf 上传文件

Spring Boot 利用 MultipartFile 的特性来接收和处理上传的文件,本示例前端页面使用 Thymeleaf 来处理。

快速上手:

1、添加依赖包

    <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>

2、application.properties配置信息

#支持的最大文件
spring.servlet.multipart.max-file-size=100MB
#文件请求最大限制
spring.servlet.multipart.max-request-size=100MB

#除过以上配置,常用的配置信息如下:
spring.servlet.multipart.enabled=true,是否支持 multipart 上传文件
spring.servlet.multipart.file-size-threshold=0,支持文件写入磁盘
spring.servlet.multipart.location=,上传文件的临时目录
spring.servlet.multipart.max-file-size=10Mb,最大支持文件大小
spring.servlet.multipart.max-request-sizee=10Mb,最大支持请求大小
spring.servlet.multipart.resolve-lazily=false,是否支持 multipart 上传文件时懒加载

3、启动类

@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 TomcatServletWebServerFactory tomcatEmbedded() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-);
}
});
return tomcat;
}
}

TomcatServletWebServerFactory() 方法主要是为了解决上传文件大于 10M 出现连接重置的问题

4、简单前端页面:

  单个文件上传页面 upload.html:

    <!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>

  多个文件上传页面 uploadMore.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body> <h1>Spring Boot files upload example</h1> <form method="POST" action="/uploadMore" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="file" name="file" /><br/><br/>
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form> </body>
</html>

上传结果页面:uploadStatus.html

<!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>

5、后台上传控制类

@Controller
public class UploadController { //文件存储目录
private String UPLOAD_PATH="E://temp//"; //跳转上传页面
@RequestMapping("/")
public String index() {
return "upload";
} @GetMapping("/more")
public String uploadMore() {
return "uploadMore";
} //多个文件上传
@RequestMapping("/uploadMore")
public String moreFileUpload(@RequestParam("file") MultipartFile[] files,RedirectAttributes redirectAttrs) {
if(files.length ==0) {
redirectAttrs.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
} for(MultipartFile file :files) {
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_PATH+file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
redirectAttrs.addFlashAttribute("message",
"You successfully uploaded all files");
return "redirect:/uploadStatus";
} //单个文件上传
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,RedirectAttributes redirectAttrs) {
if(file.isEmpty()) {
redirectAttrs.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
} try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOAD_PATH+file.getOriginalFilename());
Files.write(path, bytes);
redirectAttrs.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
} return "redirect:/uploadStatus";
} //跳转结果页面
@RequestMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}

6、运行启动类:FileUploadWebApplication

在浏览器访问:

  

  多个文件上传:

OK ,上传成功。

springboot笔记-文件上传的更多相关文章

  1. SpringBoot图文教程4—SpringBoot 实现文件上传下载

    有天上飞的概念,就要有落地的实现 概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例 文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例 ...

  2. SpringBoot 整合文件上传 elment Ui 上传组件

    SpringBoot 整合文件上传 elment Ui 上传组件 本文章记录 自己学习使用 侵权必删! 前端代码 博主最近在学 elment Ui 所以 前端使用 elmentUi 的 upload ...

  3. springboot+web文件上传和下载

    一.首先安装mysql数据库,开启web服务器. 二.pom.xml文件依赖包配置如下: <?xml version="1.0" encoding="UTF-8&q ...

  4. SpringBoot(3) 文件上传和访问

    springboot文件上传 MultipartFile file,源自SpringMVC MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutS ...

  5. SpringBoot的文件上传

    先在src/main/resources下新建一个static目录用以存放html页面,简单的html页面如下 <!DOCTYPE html> <html> <head& ...

  6. springBoot的文件上传功能

    知识点: 后台:将上传的图片写入指定服务器路径,保存起来,返回上传后的图片路径(在springBoot中,参考博客:http://blog.csdn.net/change_on/article/det ...

  7. SpringBoot下文件上传与下载的实现

    原文:http://blog.csdn.net/colton_null/article/details/76696674 SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传 ...

  8. Angular14 利用Angular2实现文件上传的前端、利用springBoot实现文件上传的后台、跨域问题

    一.angular2实现文件上传前端 Angular2使用ng2-file-upload上传文件,Angular2中有两个比较好用的上传文件的第三方库,一个是ng2-file-upload,一个是ng ...

  9. springboot 修改文件上传大小限制

    springboot 1.5.9文件上传大小限制spring:http:multipart:maxFileSize:50MbmaxRequestSize:50Mb springboot 2.0文件上传 ...

随机推荐

  1. eclipse切换工作空间

  2. BZOJ 4154: [Ipsc2015]Generating Synergy KDtree+dfs序

    多组数据真tm恶心~ 把 $dfs$序和深度分别看作横纵坐标,然后用 $KDtree$ 数点就可以了~ #include <cstdio> #include <cstring> ...

  3. liunx系统中安装lua以及torch

    一直在用pytorch,最近在做项目的时候,遇到了torch的开源代码,所以又开始不得不接触torch以及他所依赖的环境lua. liunx下lua环境的配置代码如下: ''' curl -R -O ...

  4. 利用pdfbox和poi抽取pdf、doc以及docx格式的内容

    使用pdfbox1.5.0抽取pdf格式文档内容,使用poi3.7抽取doc及docx文档内容: /** * Created by yan.shi on 2017/9/25. */ import or ...

  5. happens-before规则和as-if-serial语义

    JSR-133使用happens-before的概念来阐述操作之间的内存可见性.在JMM中,如果一个操作执行的结果需要对另一个操作可见, 那么这2个操作之间必须要存在happens-before关系. ...

  6. JPA查询getOne()与findOne()的差异以及一些小问题

    起初用Jpa 里面 getOne() 查询一个id的数据 发现查询出来的数据都是空的,但不是空的对象是按照对象默认值来的 所以导致查询不出结果 以为是数据库修改,没有及时修改实体类导致的 但是后来发现 ...

  7. TensorFlow基本计算单元——变量

    # -*- coding: utf-8 -*- import tensorflow as tf a = 3 # 创建变量 w = tf.Variable([[0.5, 1.0]]) #行向量 x = ...

  8. legend3---lavarel常用artisan命令操作

    legend3---lavarel常用artisan命令操作 一.总结 一句话总结: 帮助:php artisan可以调出帮助命令 1.npm安装后盾js? npm install hdjs node ...

  9. P3956 棋盘

    P3956 棋盘 题解 注释都在代码里了 这道题可以用DFS做,记忆化搜索,维护一个money[ ][ ] 表示到达当前节点的最小花费 不需要记录VIS,因为有一个最小值判断,如果走重复的话一定会得到 ...

  10. leetcode 621 任务调度器 Task Scheduler

    给定一个用字符数组表示的 CPU 需要执行的任务列表.其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务.任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完.CPU 在 ...