使用 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. Python天天学_04_基础四

    Python_day_04 金角大王: http://www.cnblogs.com/alex3714/articles/5765046.html ------Python是一个优雅的大姐姐 学习方式 ...

  2. 51 Nod N^N的末位数字

    1004 n^n的末位数字  题目来源: Author Ignatius.L (Hdu 1061) 基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题  收藏  关注 给 ...

  3. unittest详解(四) 批量执行用例(discover)

    前面我们说了,对于不同文件用例,我们可以通过addTest()把用例加载到一个测试套件(TestSuite)来统一执行,对于少量的文件这样做没问题,但是如果有几十上百个用例文件,这样做就太浪费时间了. ...

  4. HDU 6089 Rikka with Terrorist (线段树)

    题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=6089 题解 这波强行维护搞得我很懵逼... 扫描线,只考虑每个点能走到左上方(不包括正上方,但包括正左 ...

  5. php curl方法 支持 http https get post cookie

    //请求方式curl封装 @author Geyaru QQ 534208139 参数1:访问的URL,参数2:post数据(不填则为GET),参数3:提交的$cookies,参数4:是否返回$coo ...

  6. supsplk 服务器被植入木马 挖矿 cpu使用 700%

    最近emr集群跑任务的时候总出现 task failed ,优化sql,调提交任务参数都没解决,最后再我排查时候,发现一个从节点的cpu使用800% 经过一些列排查,发现是被注入木马了, #被人种下的 ...

  7. python 随机数详细使用,推到以及字符串,双色球小程序

    #随机数的使用import random #导入randomrandom.randint(0,9)#制定随机数0到9i=random.sample(range(1,34),6)#输出6个随机数,范围是 ...

  8. echarts之bootstrap选项卡不能显示其他标签echarts图表

    在echarts跟bootstrap选项卡整合的时候,默认第一个选中选项卡可以正常加载echarts图表,但是切换其他选项的时候不能渲染出其他选项卡echarts图表. 解决方法: 在js中添加代码: ...

  9. vue开发多页面应用

    1.添加多页面配置 在工程根路径下(package.json同目录)添加添加vue.config.js配置文件,内容为: module.exports = { pages: { index: 'src ...

  10. 《统计学习方法(李航)》讲义 第03章 k近邻法

    k 近邻法(k-nearest neighbor,k-NN) 是一种基本分类与回归方法.本书只讨论分类问题中的k近邻法.k近邻法的输入为实例的特征向量,对应于特征空间的点;输出为实例的类别,可以取多类 ...