Use Spring Boot to upload files.

Source: Internet
Author: User
Tags connection reset

Use Spring Boot to upload files.

Uploading files is one of the common application scenarios on the Internet. The most typical case is uploading portraits. Today we will take you to a small case of uploading files through Spring Boot.

1. pom package Configuration

We use the latest Spring Boot version 1.5.9, jdk 1.8, and tomcat 8.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 to 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() instanceof AbstractHttp11Protocol<?>)) {  //-1 means unlimited  ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);  } }); return tomcat; }}

The tomcatEmbedded code is used to solve the Connection reset problem when the uploaded file is larger than 10 MB. GlobalException cannot be caught.

 

For details, refer to Tomcat large file upload connection reset.

3. Compile the front-end page

Upload page

<!DOCTYPE html>

A very simple Post request, select a file in a selection box, and submit a button. The effect is as follows:

 

Upload Result Display page:

<!DOCTYPE html>

As follows:

 

4. Write the upload control class

Access 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 reads the file information through MultipartFile. If the file is empty, it jumps to the result page and provides a prompt. If it is not empty, it reads the file stream and writes it to the specified directory, finally, the results are displayed on the page.

MultipartFile is the encapsulation class for Spring upload files. It contains the binary stream and file attributes of the files. You can also configure related attributes in the configuration file. The basic configuration information is as follows:

Spring. http. multipart. enabled = true # File Upload is supported by default. spring. http. multipart. file-size-threshold = 0 # supports writing files to disks. spring. http. multipart. location = # spring. http. multipart. max-file-size = 1 Mb # maximum supported file size spring. http. multipart. max-request-size = 10 Mb # maximum supported request size

The most common configuration is the last two configurations, which limit the file upload size. If the file size is too large during upload, an exception is thrown:

 

For more configuration information, see 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 displayed on the front-end page. Using @ ControllerAdvice, You can do many things, such as global unified Exception Handling. If you are interested, you can learn about it.

6. Summary

This is a simple Demo for uploading files using Spring Boot. If you are interested, you can download the sample code and try it.

Refer:

Sample Code-github

Sample Code-code cloud

Summary

The above section describes how to use Spring Boot to upload files. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.