Uploading files should be the most frequently encountered scenario. Today, I will share with you a simple function of uploading files in Spring Boot. Without further ado, let’s start directly.
Project structure, as shown below:
pom dependencies
<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>
upload control class
@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";
}
}
Read the file information through MultipartFile
, if the file is empty, jump to the result page and give a prompt; if it is not empty, read the file stream and write it to the specified directory, and finally display the result on the page.
MultipartFile
is the encapsulation class for files uploaded by Spring. It contains information such as the binary stream and file attributes of the file. The related attributes can also be configured in the configuration file.
spring.http.multipart.enabled=true
file upload by default.spring.http.multipart.file-size-threshold=0
file writing to disk.spring.http.multipart.location=
# Temporary directory for uploading filesspring.http.multipart.max-file-size=1Mb
# Maximum supported file sizespring.http.multipart.max-request-size=10Mb
# Maximum support request size
The most commonly used are the last two configuration contents, which limit the file upload size, and an exception will be thrown when the upload exceeds the size.
configuration file
application.properties
server.port=8086
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
exception handling
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
}
Set a @ControllerAdvice
to monitor whether the file size uploaded by Multipart
is limited. When this exception occurs, a prompt will be given on the front-end page.
front page
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>
test
- Start the project, enter
localhost:8086
in the browser, the display is as follows:
- Select the file to upload, here I choose an image
- Click
Submit
to show that the upload was successful.
- Check that the picture already exists in the local folder
D:\\uploadFile\\
, so far the upload function has been realized.
Large file upload
- Test it, the file upload result exceeds the set
10M
, as shown in the figure below, the connection reset problem occurs when the uploaded file is larger than 10M, and the GlobalException of this exception content cannot be captured.
Tomcat connection reset
If deploying to Tomcat, configure maxSwallowSize to avoid this Tomcat connection reset issue. For embedded Tomcat, declare a TomcatEmbeddedServletContainerFactory with the following code:
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;
}
}
When uploading a file that exceeds the size limit again, the page throws an exception as follows:
Summarize
The simple demo about uploading files in springboot has been completed, and there are multiple file uploads. You can also try it yourself.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。