使用 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. cordova打包项目下载gradle失败

    在使用cordova打包项目的时候有时会因为网络环境原因导致下载gradle失败的情况,个人找到两种解决方案. 方案一: 根据报错的提示选择要下载的gradle去浏览器中下载,然后将gradle压缩包 ...

  2. BZOJ 3784: 树上的路径 点分治+二分+set

    很容易想出二分这个思路,但是要想办法去掉一个 $log$. 没错,空间换时间. 双指针的部分错了好几次~ Code: #include <set> #include <queue&g ...

  3. Angular 主从组件

    此刻,HeroesComponent 同时显示了英雄列表和所选英雄的详情. 把所有特性都放在同一个组件中,将会使应用“长大”后变得不可维护. 你要把大型组件拆分成小一点的子组件,每个子组件都要集中精力 ...

  4. CF 352 D 罗宾汉发钱 模拟题+贪心

    D. Robin Hood time limit per test 1 second memory limit per test 256 megabytes input standard input ...

  5. linux下安装R

    下载 版本:R3.2.2 下载地址:http://cran.rstudio.com/src/base/R-3/R-3.2.2.tar.gz 安装步骤: 解压 tar -zxvf R-3.2.2.tar ...

  6. java取小数点后两位

    package com.yonyou.sud.algorithm; import java.math.BigDecimal;import java.text.DecimalFormat;/*** ja ...

  7. 第3周Java编程总结

    1.打印输出所有的“水仙花数”,所谓“水仙花数”是指一个3位数,其中各位数字立方和等于该数本身.例如,153是一个“水仙花数”. 2. 编写Java程序,求13-23+33-43+…+973-983+ ...

  8. 微信小程序底部菜单栏的使用方法

    1.找到项目根目录的配置文件 app.json,在配置文件中加入配置代码.例如: "tabBar": { <!--底部的导航配置属性--> "color&qu ...

  9. 【CentOS】yum安装教训

    前言:本来想安装sl在新安装的centos7上,网上搜了教程,很多都是先要你yum -y update,如下: 1.更新yum源: yum -y update 2.依赖安装: wget http:// ...

  10. Dubbo Configuration

    可配置参数 http://dubbo.apache.org/zh-cn/docs/user/references/xml/introduction.html 与 spring 整合的几种方式 Spri ...