Uploading Files in Spring Boot Apps
A quick, easy guide to file uploads in Spring Boot.
Join the DZone community and get the full member experience.Join For Free
Uploading files is one of the most common operations in a web application. In this article, we will look at how to upload file from an HTML page and copy it to the file system on the server.
Creating an HTML Form With File Upload Option
enctype="multipart/form-data" is an important attribute which should be present in the
<form> that deals with uploading files.
Server-Side Code to Handle File Uploads
There will be two components in the server side:
- API Controller to receive the uploaded files.
- Code to copy the files to File System or any other file storage location.
Below is the code for the API to receive the uploaded files:
It is important to note that the value passed to the annotation
@RequestParam should match the value of the
name attribute of the
<input type="file" /> HTML element.
Let us look at the
copyFile method implementation:
MultipartFile is an interface provided by Spring framework for working with uploaded files. By default, the uploaded file is wrapped in
StandardMultipartFile, which is one of the implementations of
MultipartFile. We make use of the method
transferTo to copy the uploaded file to our desired destination on the file system.
app.document-root is defined in the file
Properties to Configure File Upload Size Limits
Spring Boot provides certain properties to configure the size limit of the file uploaded:
- spring.servlet.multipart.max-file-size – this property controls the maxmium size of the file uploaded
- spring.servlet.multipart.max-request-size – this property controls the maximum size of the request (which includes the total size of all the files uploaded).
The complete application can be found in the GitHub project here.
In next set of posts, we will see how to make use of Apache Commons File library to handle file uploads and also how to copy to other storage services like S3.
Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.