tags | projects | ||||||
---|---|---|---|---|---|---|---|
|
|
This guide walks you through the process of creating a server application that can receive multi-part file uploads.
You will create a Spring MVC application that accepts file uploads. You will also build a simple client to upload a test file.
To upload files with Servlet 3.0 containers, you need to register a MultipartConfigElement
class (which would be <multipart-config>
in web.xml). Thanks to Spring Boot, that bean is already registered and available! All you need to get started with this application is the following, empty configuration setup.
src/main/java/hello/Application.java
link:initial/src/main/java/hello/Application.java[role=include]
You will soon add a Spring MVC controller, which is why you need @SpringBootApplication
. Spring Boot automatically finds @Controller
-marked classes and registers them with the application context.
As part of auto-configuring Spring MVC, Spring Boot will create a MultipartConfigElement
bean and make itself ready for file uploads.
Note
|
MultipartConfigElement is a Servlet 3.0 standard element that defines the limits on uploading files. This component is supported by all compliant containers like Tomcat and Jetty. Later on in this guide, we’ll see how to configure its limits. |
In Spring MVC, a controller is used to handle file upload requests. The following code provides the web app with the ability to upload files.
src/main/java/hello/FileUploadController.java
link:complete/src/main/java/hello/FileUploadController.java[role=include]
The entire class is marked up with @Controller
so Spring MVC can pick it up and look for routes.
Each method is tagged with @RequestMapping
to flag the path and the HTTP action. In this case, GET
looks up the current list of uploaded files (stored in Application.ROOT
folder) and loads it into a Thymeleaf template. It provides a link to not only see, but "surf" to the file (letting the browser decide how to render).
Note
|
This example uses Java 8’s stream support combined with Java NIO operations to build paths, walk the directory of files, and generate Spring HATEOAS links. |
The handleFileUpload
method is geared to handle a multi-part message: file
. After verifying the file isn’t empty, it uses Java NIO to copy the input stream to a local file.
Note
|
In a production scenario, you more likely would store the files in a temporary location, a database, or perhaps a NoSQL store like Mongo’s GridFS. It’s is best to NOT load up the file system of your application with content. |
To build something of interest, the following Thymeleaf template is a nice example of uploading files as well as showing what’s been uploaded.
src/main/resources/templates/uploadForm.html
link:complete/src/main/resources/templates/uploadForm.html[role=include]
This template has three parts:
-
An optional message at the top where Spring MVC writes a flash-scoped messages.
-
A form allowing the user to upload files
-
A list of files supplied from the backend
When configuring file uploads, it is often useful to set limits on the size of files. Imagine trying to handle a 5GB file upload! With Spring Boot, we can configure its auto-configured MultipartConfigElement
with some property settings.
Create src/main/resources/application.properties
and make it look like this:
src/main/resources/application.properties
link:complete/src/main/resources/application.properties[role=include]
The multipart settings are constrained as follows:
-
multipart.maxFileSize
is set to 128KB, meaning total file size cannot exceed 128KB. -
multipart.maxRequestSize
is set to 128KB, meaning total request size for amultipart/form-data
cannot exceed 128KB.
Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main()
method. And along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.
src/main/java/hello/Application.java
link:complete/src/main/java/hello/Application.java[role=include]
@SpringBootApplication
is a convenience annotation that adds all of the following:
-
@Configuration
tags the class as a source of bean definitions for the application context. -
@EnableAutoConfiguration
tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. -
Normally you would add
@EnableWebMvc
for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up aDispatcherServlet
. -
@ComponentScan
tells Spring to look for other components, configurations, and services in the thehello
package, allowing it to find theFileUploadController
.
The main()
method uses Spring Boot’s SpringApplication.run()
method to launch an application. Did you notice that there wasn’t a single line of XML? No web.xml file either. This web application is 100% pure Java and you didn’t have to deal with configuring any plumbing or infrastructure.
You also want a target folder to upload files to, so there is a Java 8 lambda used to create a Boot CommandLineRunner
at startup which creates that folder.
https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_subhead.adoc https://raw.githubusercontent.com/spring-guides/getting-started-macros/master/build_an_executable_jar_with_both.adoc
That runs the server-side piece that receives file uploads. Logging output is displayed. The service should be up and running within a few seconds.
With the server running, you need to open a browser and visit http://localhost:8080/ to see the upload form. Pick a (small) file and press "Upload" and you should see the success page from the controller. Choose a file that is too large and you will get an ugly error page.
You should then see something like this in your browser window:
You successfully uploaded <name of your file>!
Congratulations! You have just written a web application that uses Spring to handle file uploads.