上传文件应该是最常常遇到的场景,明天就来和大家一起来简略做一个Spring Boot上传文件的性能,废话不多说,间接开始。
我的项目构造,如下图:
pom 依赖
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
上传管制类
@Controller
public class UploadController
{
private static String UPLOADED_FOLDER = "D:\\uploadFile\\";
@GetMapping("/")
public String index()
{
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes)
{
if (file.isEmpty())
{
redirectAttributes.addFlashAttribute("message", "请抉择文件上传");
return "redirect:uploadStatus";
}
try
{
byte[] bytes = file.getBytes();
Path dir = Paths.get(UPLOADED_FOLDER);
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
if (!Files.exists(dir))
{
Files.createDirectories(dir);
}
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message","上传胜利,文件的名称:" + file.getOriginalFilename());
}
catch (IOException e)
{
redirectAttributes.addFlashAttribute("message", "服务异样");
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus()
{
return "uploadStatus";
}
}
通过MultipartFile
读取文件信息,如果文件为空跳转到后果页并给出提醒;如果不为空读取文件流并写入到指定目录,最初将后果展现到页面。
MultipartFile
是Spring上传文件的封装类,蕴含了文件的二进制流和文件属性等信息,在配置文件中也可对相干属性进行配置。
spring.http.multipart.enabled=true
#默认反对文件上传.spring.http.multipart.file-size-threshold=0
#反对文件写入磁盘.spring.http.multipart.location=
# 上传文件的长期目录spring.http.multipart.max-file-size=1Mb
# 最大反对文件大小spring.http.multipart.max-request-size=10Mb
# 最大反对申请大小
最罕用的是最初两个配置内容,限度文件上传大小,上传时超过大小会抛出异样。
配置文件
application.properties
server.port=8086
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
异样解决
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
}
设置一个@ControllerAdvice
用来监控Multipart
上传的文件大小是否受限,当呈现此异样时在前端页面给出提醒。
前端页面
upload.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>上传文件</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>上传状态</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
测试
- 启动我的项目,浏览器输出
localhost:8086
,显示如下:
- 抉择文件进行上传,这里我抉择了一张图片
- 点击
Submit
,显示上传胜利。
- 查看本地文件夹
D:\\uploadFile\\
中曾经有了该图片,至此该上传性能已实现。
大文件上传
- 测试一下,超过设置的
10M
的文件上传后果,如下图,上传文件大于10M呈现连贯重置的问题,此异样内容 GlobalException 也捕捉不到。
Tomcat连贯重置
如果部署到Tomcat,请配置maxSwallowSize以防止此Tomcat连贯重置问题。 对于嵌入式Tomcat,申明一个TomcatEmbeddedServletContainerFactory,如下代码:
package com.cy;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class SpringbootUploadApplication
{
public static void main(String[] args)
{
SpringApplication.run(SpringbootUploadApplication.class, args);
}
@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
再次上传超过大小限度的文件,页面抛出异样如下:
总结
对于springboot上传文件简略的demo实现了,还有多文件上传,小伙伴们也能够本人去试试。
发表回复