Spring Boot File Upload Example
1. Create Spring Boot project
OK. Project has been created.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.o7planning</groupId>
<artifactId>SpringBootFileUpload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootFileUpload</name>
<description>Spring Boot + File Upload Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
SpringBootFileUploadApplication.java
package org.o7planning.sbfileupload;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootFileUploadApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootFileUploadApplication.class, args);
}
}
2. Configure file size
Spring Boot has automatically configured the necessary libraries so that you can build the file upload function. The default size of the file is limited to 128KB, so you need to configure to change the value for this parameter. Add the following properties to the application.properties file.
application.properties
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
The maximum file size is 5GB.
3. Form & Controller
MyUploadForm.java
package org.o7planning.sbfileupload.form;
import org.springframework.web.multipart.MultipartFile;
public class MyUploadForm {
private String description;
// Upload files.
private MultipartFile[] fileDatas;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public MultipartFile[] getFileDatas() {
return fileDatas;
}
public void setFileDatas(MultipartFile[] fileDatas) {
this.fileDatas = fileDatas;
}
}
MyFileUploadController.java
package org.o7planning.sbfileupload.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.o7planning.sbfileupload.form.MyUploadForm;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class MyFileUploadController {
@RequestMapping(value = "/")
public String homePage() {
return "index";
}
// GET: Show upload form page.
@RequestMapping(value = "/uploadOneFile", method = RequestMethod.GET)
public String uploadOneFileHandler(Model model) {
MyUploadForm myUploadForm = new MyUploadForm();
model.addAttribute("myUploadForm", myUploadForm);
return "uploadOneFile";
}
// POST: Do Upload
@RequestMapping(value = "/uploadOneFile", method = RequestMethod.POST)
public String uploadOneFileHandlerPOST(HttpServletRequest request, //
Model model, //
@ModelAttribute("myUploadForm") MyUploadForm myUploadForm) {
return this.doUpload(request, model, myUploadForm);
}
// GET: Show upload form page.
@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.GET)
public String uploadMultiFileHandler(Model model) {
MyUploadForm myUploadForm = new MyUploadForm();
model.addAttribute("myUploadForm", myUploadForm);
return "uploadMultiFile";
}
// POST: Do Upload
@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public String uploadMultiFileHandlerPOST(HttpServletRequest request, //
Model model, //
@ModelAttribute("myUploadForm") MyUploadForm myUploadForm) {
return this.doUpload(request, model, myUploadForm);
}
private String doUpload(HttpServletRequest request, Model model, //
MyUploadForm myUploadForm) {
String description = myUploadForm.getDescription();
System.out.println("Description: " + description);
// Root Directory.
String uploadRootPath = request.getServletContext().getRealPath("upload");
System.out.println("uploadRootPath=" + uploadRootPath);
File uploadRootDir = new File(uploadRootPath);
// Create directory if it not exists.
if (!uploadRootDir.exists()) {
uploadRootDir.mkdirs();
}
MultipartFile[] fileDatas = myUploadForm.getFileDatas();
//
List<File> uploadedFiles = new ArrayList<File>();
List<String> failedFiles = new ArrayList<String>();
for (MultipartFile fileData : fileDatas) {
// Client File Name
String name = fileData.getOriginalFilename();
System.out.println("Client File Name = " + name);
if (name != null && name.length() > 0) {
try {
// Create the file at server
File serverFile = new File(uploadRootDir.getAbsolutePath() + File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(fileData.getBytes());
stream.close();
//
uploadedFiles.add(serverFile);
System.out.println("Write file: " + serverFile);
} catch (Exception e) {
System.out.println("Error Write file: " + name);
failedFiles.add(name);
}
}
}
model.addAttribute("description", description);
model.addAttribute("uploadedFiles", uploadedFiles);
model.addAttribute("failedFiles", failedFiles);
return "uploadResult";
}
}
4. Thymeleaf Templates
_menu.html
<div xmlns:th="http://www.thymeleaf.org"
style="border:1px solid #ccc;padding:5px;">
<a th:href="@{/uploadOneFile}">Upload One File</a>
|
<a th:href="@{/uploadMultiFile}">Upload Multi File</a>
</div>
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot File Upload Example</title>
</head>
<body>
<th:block th:include="/_menu"></th:block>
<h3>Spring Boot File Upload Example</h3>
<ul>
<li><a th:href="@{/uploadOneFile}">Upload One File Example</a></li>
<li><a th:href="@{/uploadMultiFile}">Upload Multiple Files Example</a></li>
</ul>
</body>
</html>
uploadOneFile.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Upload One File</title>
</head>
<body>
<th:block th:include="/_menu"></th:block>
<h3>Upload One File:</h3>
<!-- MyUploadForm -->
<form th:object="${myUploadForm}" method="POST"
action="" enctype="multipart/form-data">
Description:
<br>
<input th:field="*{description}" style="width:300px;"/>
<br/><br/>
File to upload: <input th:field="*{fileDatas}" type="file"/>
<br />
<input type="submit" value="Upload">
</form>
</body>
</html>
uploadMultiFile.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Upload Multi File</title>
</head>
<body>
<th:block th:include="/_menu"></th:block>
<h3>Upload Multiple File:</h3>
<!-- MyUploadForm -->
<form th:object="${myUploadForm}" method="POST"
action="" enctype="multipart/form-data">
Description:
<br>
<input th:field="*{description}" style="width:300px;"/>
<br/><br/>
File to upload (1): <input th:field="*{fileDatas}" type="file"/><br />
File to upload (2): <input th:field="*{fileDatas}" type="file"/><br />
File to upload (3): <input th:field="*{fileDatas}" type="file"/><br />
File to upload (4): <input th:field="*{fileDatas}" type="file"/><br />
File to upload (5): <input th:field="*{fileDatas}" type="file"/><br />
<input type="submit" value="Upload">
</form>
</body>
</html>
uploadResult.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Upload Result</title>
</head>
<body>
<th:block th:include="/_menu"></th:block>
Description: <span th:utext="${description}"></span>
<br/>
<h3>Uploaded Files:</h3>
<ul th:each="file : ${uploadedFiles}">
<li th:utext="${file}"></li>
</ul>
<h3>Failed:</h3>
<ul th:each="file : ${failedFiles}">
<li style="color:red;" th:utext="${file}"></li>
</ul>
</body>
</html>
Spring Boot Tutorials
- Install Spring Tool Suite for Eclipse
- Spring Tutorial for Beginners
- Spring Boot Tutorial for Beginners
- Spring Boot Common Properties
- Spring Boot and Thymeleaf Tutorial with Examples
- Spring Boot and FreeMarker Tutorial with Examples
- Spring Boot and Groovy Tutorial with Examples
- Spring Boot and Mustache Tutorial with Examples
- Spring Boot and JSP Tutorial with Examples
- Spring Boot, Apache Tiles, JSP Tutorial with Examples
- Use Logging in Spring Boot
- Application Monitoring with Spring Boot Actuator
- Create a Multi Language web application with Spring Boot
- Use multiple ViewResolvers in Spring Boot
- Use Twitter Bootstrap in Spring Boot
- Spring Boot Interceptors Tutorial with Examples
- Spring Boot, Spring JDBC and Spring Transaction Tutorial with Examples
- Spring JDBC Tutorial with Examples
- Spring Boot, JPA and Spring Transaction Tutorial with Examples
- Spring Boot and Spring Data JPA Tutorial with Examples
- Spring Boot, Hibernate and Spring Transaction Tutorial with Examples
- Integrating Spring Boot, JPA and H2 Database
- Spring Boot and MongoDB Tutorial with Examples
- Use Multiple DataSources with Spring Boot and JPA
- Use Multiple DataSources with Spring Boot and RoutingDataSource
- Create a Login Application with Spring Boot, Spring Security, Spring JDBC
- Create a Login Application with Spring Boot, Spring Security, JPA
- Create a User Registration Application with Spring Boot, Spring Form Validation
- Example of OAuth2 Social Login in Spring Boot
- Run background scheduled tasks in Spring
- CRUD Restful Web Service Example with Spring Boot
- Spring Boot Restful Client with RestTemplate Example
- CRUD Example with Spring Boot, REST and AngularJS
- Secure Spring Boot RESTful Service using Basic Authentication
- Secure Spring Boot RESTful Service using Auth0 JWT
- Spring Boot File Upload Example
- Spring Boot File Download Example
- Spring Boot File Upload with jQuery Ajax Example
- Spring Boot File Upload with AngularJS Example
- Create a Shopping Cart Web Application with Spring Boot, Hibernate
- Spring Email Tutorial with Examples
- Create a simple Chat application with Spring Boot and Websocket
- Deploy Spring Boot Application on Tomcat Server
- Deploy Spring Boot Application on Oracle WebLogic Server
- Install a free Let's Encrypt SSL certificate for Spring Boot
- Configure Spring Boot to redirect HTTP to HTTPS
- Fetch data with Spring Data JPA DTO Projections
Show More