Spring Boot File Upload example
This example shows how to create a Spring Boot Web Application that uploads file. We will create a FileUploadController and FileService to upload a file.
Step 1) Add below dependencies in pom.xml
<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> </dependencies>
Step 2) Create FileUploadApplication class
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FileUploadApplication { public static void main(String[] args) { SpringApplication.run(FileUploadApplication.class, args); } }
Step 3) Create uploadForm.html file and put it under src/main/resources/templates directory
uploadForm.html is a HTML5 page which serves as the file upload form page for FileUploadApplication
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <div th:if="${message}"> <h2 th:text="${message}"/> </div> <div> <form method="POST" enctype="multipart/form-data" action="/"> <table> <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr> <tr><td></td><td><input type="submit" value="Upload" /></td></tr> </table> </form> </div> </html>
Step 4) Create FileServiceImpl classes
package com.example.demo; import org.springframework.web.multipart.MultipartFile; public interface FileService { void save(MultipartFile file); }
package com.example.demo; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; @Service public class FileServiceImpl implements FileService { public void save(MultipartFile file) { try { Files.write(Paths.get("C://Data.txt"), file.getBytes()); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("File saved successfully"); } }
Step 5) Create FileUploadController class
FileUploadController contains one GET request mapping to load file upload form and another POST request mapping to handle file upload.
package com.example.demo; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class FileUploadController { @Autowired private FileService fileService; @GetMapping("/") public String uploadFiles(Model model) throws IOException { return "uploadForm"; } @PostMapping("/") public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { fileService.save(file); redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!"); return "redirect:/"; } }
Step 6) Running FileUploadApplication
To Run this Spring Boot application from command prompt, use following command → java -jar demo-0.0.1-SNAPSHOT.jarStep 7) Testing FileUploadApplication
Open any browser and launch http://localhost:8080. You will see below page.
Choose file and click on upload button. Check that file is saved to specified location.
Controlling File Upload Limits
When configuring file uploads, you can set limits on the size of file. To achieve this you need to add the following properties to your existing properties settings (in application.properties under src/main/resources) file.
spring.servlet.multipart.max-file-size=128KB spring.servlet.multipart.max-request-size=128KB
If you try to upload a file with size more than 128KB, you will get below error
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Fri Apr 17 19:20:03 IST 2020 There was an unexpected error (type=Internal Server Error, status=500). Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (38223) exceeds the configured maximum (1024)
References :
Uploading files