Uploading files is one of the common scenarios on the Internet. The most typical situation is uploading avatars, etc. Today, I will take you to do a small case of uploading files in Spring Boot.
1. Pom package configuration
We use Spring Boot's latest version 1.5.9, jdk uses 1.8, tomcat8.0.
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.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 is introduced as the page template engine and write some simple upload examples.
2. Startup class settings
@SpringBootApplicationpublic class FileUploadWebApplication { public static void main(String[] args) throws Exception { SpringApplication.run(FileUploadWebApplication.class, args); } //Tomcat large file upload connection reset @Bean public TomcatEmbeddedServletContainerFactory tomcatEmbedded() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> { if ((connector.getProtocolHandler() instance of AbstractHttp11Protocol<?>)) { //-1 means unlimited ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1); } }); return tomcat; }}TomcatEmbedded code is to solve the problem of connection reset when uploading files larger than 10M. This exception content is also not captured by GlobalException.
Detailed content reference: Tomcat large file upload connection reset
3. Write a front-end page
Upload page
<!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>
A very simple Post request, a selection box to select a file, and a submit button, the effect is as follows:
Upload result display page:
<!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>The renderings are as follows:
4. Write upload control class
Visit localhost to automatically jump to the upload page:
@GetMapping("/")public String index() { return "upload";}Upload service processing
@PostMapping("/upload") public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:uploadStatus"; } try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { e.printStackTrace(); } return "redirect:/uploadStatus";}The above code means that the file information is read through MultipartFile, if the file is empty, jump to the result page and give a prompt; if the file stream is not empty and written to the specified directory, the result will be displayed on the page.
MultipartFile is an encapsulation class for Spring uploaded files, which contains information such as binary streams and file attributes. Relevant attributes can also be configured in the configuration file. The basic configuration information is as follows:
spring.http.multipart.enabled=true #Default supported file upload.spring.http.multipart.file-size-threshold=0 #Support file writing to disk.spring.http.multipart.location= # Temporary directory for uploading files spring.http.multipart.max-file-size=1Mb # Maximum supported file size spring.http.multipart.max-request-size=10Mb # Maximum supported request size
The most commonly used are the last two configuration contents, which limit the file upload size. If the file exceeds the size, an exception will be thrown when uploading:
For more configuration information, please refer to here: Common application properties
5. Exception handling
@ControllerAdvicepublic 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 is given on the front-end page. You can do a lot of things with @ControllerAdvice, such as global unified exception handling, etc. Interested students can come down to learn about it.
6. Summary
This simple demo of uploading files using Spring Boot is completed. Interested students can download the sample code and try it.
refer to:
Sample code - github
Sample code-Code cloud
Summarize
The above is what the editor introduced to you using Spring Boot file upload function. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!