springBoot单文件上传和多文件上传
1. 开发工具版本介绍
springBoot版本:1.5
JDK版本:1.8
tomcat版本:7.0
2. pom配置
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.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. application.properties配置
#thymeleaf
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#上传文件
#默认支持文件上传.
spring.http.multipart.enabled=true
#支持文件写入磁盘.
spring.http.multipart.file-size-threshold=0
#上传文件的临时目录
spring.http.multipart.location=
# 最大支持文件大小
spring.http.multipart.max-file-size=1Mb
3.启动类配置
@SpringBootApplication
public class FileUploadWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(FileUploadWebApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory tomcatEmbedded() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
tomcatEmbedded解决上传文件大于10M出现连接重置的问题。此异常内容 GlobalException 也捕获不到。
springBoot1.5版本使用TomcatEmbeddedServletContainerFactory
springBoot2.0版本使用TomcatServletWebServerFactory
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>
上传结果页面: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.业务处理类
/**
* 跳转单文件上传页面
* @return
*/
@GetMapping("/")
public String index() {
return "upload";
}
/**
* 单文件上传
* @param file
* @param model
* @return
*/
@PostMapping("/uploadFile")
public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) {
if (file.isEmpty()) {
model.addAttribute("message", "Please select a file to upload");
return "uploadStatus";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("D:/springUpload/" + file.getOriginalFilename());
Files.write(path, bytes);
model.addAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (Exception e) {
e.printStackTrace();
}
return "uploadStatus";
}
6.异常类处理
package com.example.demo.controller.upload;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, Model model) {
model.addAttribute("message", e.getCause().getMessage());
return "uploadStatus";
}
}
多文件处理
多文件上传更简单,只需要两个步骤,如下
- 前端上传控件添加multiple=“multiple”
<input type="file" name="file" multiple="multiple" />
- 处理类接收使用数组MultipartFile[] files,循环每一个file就可以了
@PostMapping("/uploadManyFile") public String manyFileUpload(@RequestParam("file") MultipartFile[] files, Model model) { if (files.length == 0) { model.addAttribute("message", "Please select a file to upload"); return "uploadStatus"; } try { Path path = null; byte[] bytes = null; for (MultipartFile file : files) { bytes = file.getBytes(); path = Paths.get("D:/springUpload/" + file.getOriginalFilename()); Files.write(path, bytes); } model.addAttribute("message", "You successfully uploaded many file"); } catch (Exception e) { e.printStackTrace(); } return "uploadStatus"; }