Web server is returning an unknown error Error code 520
There is an unknown connection issue between Cloudflare and the origin web server. As a result, the web page can not be displayed.
What can I do?
If you are a visitor of this website:
Please try again in a few minutes.
If you are the owner of this website:
There is an issue between Cloudflare’s cache and your origin web server. Cloudflare monitors for these errors and automatically investigates the cause. To help support the investigation, you can pull the corresponding error log from your web server and submit it our support team. Please include the Ray ID (which is at the bottom of this error page). Additional troubleshooting resources.
Cloudflare Ray ID: 7a73722a05a768b5 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Spring Boot REST API File Upload/Save Example
This guide shows you how to upload/save a file using Spring Boot REST API. To upload files via HTTP multi-part requests will be handled by MultipartFile . It is a representation of an uploaded file received in a multipart request through which we can get the file contents and stored in the database or file system.
P.S. Tested on Windows environment.
What we’ll build
We will create a Spring Boot web application that accepts the file uploads and save files into the database or file system location.
Technology Used
Find the list of all technologies used in this application.
- Spring Tool Suite 4
- JDK 8
- Spring Boot 2.2.4.RELEASE
- Spring Data JPA 2.2.4.RELEASE
- MySQL Database
- Maven 3
Dependencies Required
These the basic dependencies that required in this application, add them to your pom.xml.
1. Save in the File System
To save/copy/upload file in the system directory, follow the below steps;
- Get the bytes of the file which comes in HTTP multi-part request by calling getBytes() method of MultipartFile interface. It returns the byte array of the file.
- Prepare the path (directory location) where you want to save/copy/upload the file. getOriginalFilename() method return original name of file.
- Write byte array to the desired location via Files.write(path, bytes);
2. Save in the Database
Similarly, we can save the multi-part form data into the database table. We only need to take care of the column definition where we insert the file.
2.1 Entity
Suppose, we want to save id, name and profile photo of Prime Minister of India, so the entity class will look like:
Why @Lob annotation used here? Because when want to store large dataset/file object into the database table, we need huge space. LOB stands for Large OBject and the maximum capacity of a LOB is (4 gigabytes-1) bytes.
It will result the following SQL definition.
2.2 Repository
2.3 Controller
The first step is the same we discussed above:
- Get the bytes of the file.
- Set the HTTP multi-part form data to an entity.
- Call the save(Entity e) method of the Spring Data JpaRepository interface.
Here is the complete controller class which caters the both 1. Upload file to classpath/system directory and 2. Inter the form data and file into the database table.
Run the application
The SpringBootUploadFileAppication class contains the main method and responsible to start the application.
Test the application
Let’s test the application, executing the above class and it will start the application then follow the below steps:
Spring Boot File Upload / Download with JPA, Hibernate, and MySQL database
This article is a continuation of an earlier article where I’ve shown how to upload files and store them in the local filesystem.
We’ll reuse most of the code and concepts described in the last article. So I highly recommend you to go through that before reading this one.
The complete code is available in the Github repository.
Following is the directory structure of the complete application for your reference —
JPA and MySQL dependencies
Since we’ll be storing files in MySQL database, we’ll need JPA and MySQL dependencies along with Web dependency. So make sure that your pom file contains the following dependencies —
If you’re building the project from scratch, you can generate the project skeleton from Spring Initialzr website.
Configuring the Database and Multipart File properties
Next, we need to configure the MySQL database url, username, and password. You can configure that in the src/main/resources/application.properties file —
The above properties file also has Multipart file properties. You can make changes to these properties as per your requirements.
Let’s create a DBFile entity to model the file attributes that will be stored in the database —
Note that, the file’s contents will be stored as a byte array in the database.
Next, we need to create a repository to save files in the database and retrieve them back —
The following DBFileStorageService contains methods to store and retrieve files to/from the database —
FileController (File upload/download REST APIs)
Finally, following are the Rest APIs to upload and download files —
I’ll be reusing the complete front-end code that I demonstrated in the first part of this article. You should check out the first article to learn more about the front-end code, or download it from Github.
Once you have the front-end code in place, type the following command to run the application —
Uploading Files
This guide walks you through the process of creating a server application that can receive HTTP multi-part file uploads.
What You Will Build
You will create a Spring Boot web application that accepts file uploads. You will also build a simple HTML interface to upload a test file.
What You Need
About 15 minutes
A favorite text editor or IDE
You can also import the code straight into your IDE:
How to complete this guide
Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
To start from scratch, move on to Starting with Spring Initializr.
To skip the basics, do the following:
Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-uploading-files.git
cd into gs-uploading-files/initial
When you finish, you can check your results against the code in gs-uploading-files/complete .
Starting with Spring Initializr
You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
Click Dependencies and select Spring Web and Thymeleaf.
Click Generate.
Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
| If your IDE has the Spring Initializr integration, you can complete this process from your IDE. |
| You can also fork the project from Github and open it in your IDE or other editor. |
Create an Application Class
To start a Spring Boot MVC application, you first need a starter. In this sample, spring-boot-starter-thymeleaf and spring-boot-starter-web are already added as dependencies. To upload files with Servlet containers, you need to register a MultipartConfigElement class (which would be <multipart-config> in web.xml). Thanks to Spring Boot, everything is auto-configured for you!
All you need to get started with this application is the following UploadingFilesApplication class (from src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java ):
As part of auto-configuring Spring MVC, Spring Boot will create a MultipartConfigElement bean and make itself ready for file uploads.
Create a File Upload Controller
The initial application already contains a few classes to deal with storing and loading the uploaded files on disk. They are all located in the com.example.uploadingfiles.storage package. You will use those in your new FileUploadController . The following listing (from src/main/java/com/example/uploadingfiles/FileUploadController.java ) shows the file upload controller:
The FileUploadController class is annotated with @Controller so that Spring MVC can pick it up and look for routes. Each method is tagged with @GetMapping or @PostMapping to tie the path and the HTTP action to a particular controller action.
GET / : Looks up the current list of uploaded files from the StorageService and loads it into a Thymeleaf template. It calculates a link to the actual resource by using MvcUriComponentsBuilder .
GET /files/
POST / : Handles a multi-part message file and gives it to the StorageService for saving.
| In a production scenario, you more likely would store the files in a temporary location, a database, or perhaps a NoSQL store (such as Mongo’s GridFS). It is best to NOT load up the file system of your application with content. |
You will need to provide a StorageService so that the controller can interact with a storage layer (such as a file system). The following listing (from src/main/java/com/example/uploadingfiles/storage/StorageService.java ) shows that interface:
Creating an HTML Template
The following Thymeleaf template (from src/main/resources/templates/uploadForm.html ) shows an example of how to upload files and show what has been uploaded:
This template has three parts:
An optional message at the top where Spring MVC writes a flash-scoped message.
A form that lets the user upload files.
A list of files supplied from the backend.
Tuning File Upload Limits
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 tune its auto-configured MultipartConfigElement with some property settings.
Add the following properties to your existing properties settings (in src/main/resources/application.properties ):
The multipart settings are constrained as follows:
spring.servlet.multipart.max-file-size is set to 128KB, meaning total file size cannot exceed 128KB.
spring.servlet.multipart.max-request-size is set to 128KB, meaning total request size for a multipart/form-data cannot exceed 128KB.
Run the Application
You want a target folder to which to upload files, so you need to enhance the basic UploadingFilesApplication class that Spring Initializr created and add a Boot CommandLineRunner to delete and re-create that folder at startup. The following listing (from src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java ) shows how to do so:
@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. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet .
@ComponentScan : Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.
Build an executable JAR
You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you use Gradle, you can run the application by using ./gradlew bootRun . Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:
If you use Maven, you can run the application by using ./mvnw spring-boot:run . Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:
| The steps described here create a runnable JAR. You can also build a classic WAR file. |
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. You should see the success page from the controller. If you choose a file that is too large, you will get an ugly error page.
You should then see a line resembling the following in your browser window:
“You successfully uploaded <name of your file>!”
Testing Your Application
There are multiple ways to test this particular feature in our application. The following listing (from src/test/java/com/example/uploadingfiles/FileUploadTests.java ) shows one example that uses MockMvc so that it does not require starting the servlet container:
In those tests, you use various mocks to set up the interactions with your controller and the StorageService but also with the Servlet container itself by using MockMultipartFile .
For an example of an integration test, see the FileUploadIntegrationTests class (which is in src/test/java/com/example/uploadingfiles ).
Summary
Congratulations! You have just written a web application that uses Spring to handle file uploads.
See Also
The following guides may also be helpful:
Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.