Spring Boot upload file with form example 2016-04-17 22:29

For most project uploading file is a commonly-used function. In this page I will show you how to upload a file in Spring Boot. It works if you just use SpringMVC in your project. I use jsp as page, so if you don't kow how to use jsp in Spring Boot you can click here for more detail.

Project structure

│  ├─java
│  │  └─com
│  │      └─henry
│  │          └─upload
│  │                  SampleUploadController.java
│  │
│  └─resources
│      │  application.properties
│      │
│      └─META-INF
│          └─resources
│              └─WEB-INF
│                  └─jsp
│                          upload.jsp

dependencies in pom file


java code

public class SampleUploadController extends SpringBootServletInitializer {

    public String index() {
        return "upload";

    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            String content = new String(file.getBytes());
            return "file name:" + file.getOriginalFilename() + "<br> content:" + content;
        } catch (IOException e) {
        return "file name:" + file.getOriginalFilename() +"<br> read file content error.";

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SampleUploadController.class, args);

application properties file

multipart.maxFileSize: 15MB
multipart.maxRequestSize: 15MB

multipart.maxFileSize specifies the maximum size permitted for uploaded files. The default is 1Mb. multipart.maxRequestSize specifies the maximum size allowed for multipart/form-data requests. The default is 10Mb

jps file

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>upload file</title>
<form action="upload" method="POST" enctype="multipart/form-data">
    <input type="file" id="file" name="file">
    <input type="submit">

Run the main method and visit http://localhost:8080/, click upload button choose the file you want upload then click submit. You will get the file name and content.