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]
This class is used to configure the server application that will receive file uploads, thanks to the @Configuration
annotation.
You will soon add a Spring MVC controller, which is why you need both @EnableAutoConfiguration
and @ComponentScan
. Normally, you would use @EnableWebMvc
for a Spring MVC application, but Spring Boot automatically adds this annotation when it detects spring-webmvc on your classpath. @ComponentScan
makes it possible to automatically find @Controller
-marked classes.
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
returns a very simple message indicating the POST
operation is available.
The handleFileUpload
method is geared to handle a two-part message: name
and file
. It checks to make sure the file is not empty, and if it is empty, the method grabs the bytes. Next, it writes them out through a BufferedOutputStream
.
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. You also need controls in place to avoid filling up the filesystem while also protecting yourself from vulnerabilities such as uploading executables and overwriting existing files. |
When configuring file uploads, its often useful to set limits on the size of files. Imagine trying to handle a 5GB file upload! We Spring Boot, we can configure it’s auto-configured MultipartConfigElement
with some property settings.
Create src/main/resources/application.properties
and make it look like this:
src/main/resources/application.properties
include::complete/src/main/resources/application.properties
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.
Create an "index.html" file in src/main/resources/static
(so it ends up in the classpath under /static
):
src/main/resources/static/index.html
link:complete/src/main/resources/static/index.html[role=include]
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]
The main()
method defers to the SpringApplication
helper class, providing Application.class
as an argument to its run()
method. This tells Spring to read the annotation metadata from Application
and to manage it as a component in the Spring application context.
The @ComponentScan
annotation tells Spring to search recursively through the hello
package and its children for classes marked directly or indirectly with Spring’s @Component
annotation. This directive ensures that Spring finds and registers the FileUploadController
, because it is marked with @Controller
, which in turn is a kind of @Component
annotation.
The @EnableAutoConfiguration
annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC DispatcherServlet
is configured and registered for you — no web.xml
necessary! Spring Boot configures Spring’s battle tested DispatcherServlet
with multipart file upload support out of the box. Auto-configuration is a powerful, flexible mechanism. See the API documentation for further details.
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>!
The controller itself doesn’t print anything out, but instead returns the message posted to the browser.