Uploading files is one of the most frequently used scenes in the Internet, and the most typical case is uploading avatars and so on, today with a small case that takes everyone to do a spring boot upload file.
1, POM package configuration
We use the latest version of Spring boot 1.5.9, JDK use 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>
Introduced spring-boot-starter-thymeleaf
to do page template engine, write some simple upload example.
2. Startup class Settings
@SpringBootApplication Public classfileuploadwebapplication { Public Static void Main(string[] args)throwsException {springapplication.Run(Fileuploadwebapplication.class, args); }//tomcat Large File upload connection reset @Bean PublicTomcatembeddedservletcontainerfactorytomcatembedded() {Tomcatembeddedservletcontainerfactory Tomcat =New tomcatembeddedservletcontainerfactory(); Tomcat.addconnectorcustomizers((Tomcatconnectorcustomizer) connector, {if(connector.Getprotocolhandler()instanceofabstracthttp11protocol<?>)) {//-1 means unlimited((abstracthttp11protocol<?>) connector.Getprotocolhandler()).setmaxswallowsize(-1); } });returnTomcat }}
Tomcatembedded This code is to solve the problem of uploading files larger than 10M connection reset. This exception content Globalexception is also not captured.
For more information: Tomcat large file Upload connection reset
3. Writing the front page
Upload page
<! DOCTYPEHtml>xmlns:th="http://www.thymeleaf.org"><body>Spring Boot File Upload Example<formmethod="POST"action="/upload"enctype="Multipart/form-data"> <inputtype="File"name="File" /><br/><br/> <inputtype="Submit"value="Submit" /></form></body>
Very simple a POST request, a selection box to select a file, a submit button, the effect is as follows:
Upload Results Display page:
<!DOCTYPE html> lang="en" xmlns:th="http://www.thymeleaf.org"><body>Spring Boot - Upload Status<div th:if="${message}"> th:text="${message}"/></div></body>
As follows:
4, write the Upload control class
Access localhost automatically jumps to the upload page:
@GetMapping("/")publicindex() { return"upload";}
Upload Business Processing
@PostMapping("/upload") PublicStringSinglefileupload(@RequestParam("File") multipartfile file, Redirectattributes redirectattributes) {if(file.IsEmpty()) {redirectattributes.Addflashattribute("Message","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 by MultipartFile
reading the file information, if the file is empty to jump to the results page and give a hint, if the file stream is not empty and written to the specified directory, the result is displayed to the page.
MultipartFile
Is the spring upload file encapsulation class, contains the file's binary stream and file attributes and other information, in the configuration file can also be configured for related properties, basic configuration information as follows:
spring.http.multipart.enabled=true
#默认支持文件上传.
spring.http.multipart.file-size-threshold=0
#支持文件写入磁盘.
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 Support request size
The most common is the last two configuration content, limit file upload size, upload more than the size will throw an exception:
For more configuration information refer here: Common application properties
5. Exception Handling
@ControllerAdvicepublicclass GlobalExceptionHandler { @ExceptionHandler(MultipartException.class) publichandleError1(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return"redirect:/uploadStatus"; }}
Sets a @ControllerAdvice
Multipart
limit on whether the file size of the upload is limited and prompts you on the front page when this exception occurs. Use @ControllerAdvice
can do a lot of things, such as the global unified exception processing, interested students can come down to understand.
6. Summary
A simple demo that uses spring boot to upload a file is finished, and interested students can download the sample code to try it out.
Reference :
Spring Boot File Upload Example
Sample Code-github
Sample code-Cloud Code
Springboot (17): Uploading Files using spring boot