使用 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. QT:QSS完全无效的原因

    QSS的文件格式不是UTF-8,导致读取到的文件中字符串出现乱码.

  2. codevs 5960 信使x

    题目描述 Description •战争时期,前线有n个哨所,每个哨所可能会与其他若干个哨所之间有通信联系.信使负责在哨所之间传递信息,当然,这是要花费一定时间的(以天为单位).指挥部设在第一个哨所. ...

  3. 015 pip的使用

    目录 一.配置pip环境变量 二.Cmd终端使用pip 三.Pycharm使用pip 四.Jupyter使用pip 如果把python假想成一部手机,那么pip就是这部手机上的应用管家/APP,他可以 ...

  4. Wordpress可以用来做什么?

    WordPress本身只是一款开源的.基于PHP的博客软件,但是由于WordPress的源码开源.结构优良.插件丰富.主题繁多,以至于是 WordPress成为世界上最流行的博客程序.<Word ...

  5. 实现图像添加label

    void CmapwingisTest2View::OnToolsAddTiffLayer() { TCHAR szFilters[]= _T("TIFF Files (*.tif)|*.t ...

  6. leetcode-easy-others-20 Valid Parentheses

    mycode   95.76% class Solution(object): def isValid(self, s): """ :type s: str :rtype ...

  7. 转自B站 真希望我在20岁就懂得的10个人生道理 主讲:王魄

    视频地址:https://www.bilibili.com/video/av65194244?from=search&seid=15261178568916939794 这位阿姨讲得还行,特别 ...

  8. 【转】C++ typedef typename 作用

    转:https://blog.csdn.net/zhangxiao93/article/details/50569924 and GOOD: https://blog.csdn.net/vanturm ...

  9. [flask]jinjia2-模板 url_for的使用

    url_for是什么? url_for()用于生成URL的函数,是Flask内置模板的1个全局函数 url_for()用来获取URL,用法和在Python脚本中相同.url_for的参数是视图的端点( ...

  10. zabbix服务端安装

    1.安装zabbix服务(1)先rpm安装lamp环境 yum install -y httpd mysql mysql-libs php php-mysql mysql-server php-bcm ...