EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring boot file upload
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring boot grpc
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring boot file upload

Spring boot file upload

Introduction to Spring boot file upload

In Spring boot, we can upload files to the server by making our HTTP request multipart. This type of request is used to send the binary files and text files to the server; hence we need to use multipart requests for this. In spring boot, we have to make necessary changes and configurations in order to make this work. This requires a bit of configuration in our application; the request parsing method will be a bit different from others we have seen so far. Sometimes we may require to upload some files to the server because we can use large data inside it to store; also, we can upload videos by the use of this type of request; they are basically designed to handle such requests in the web application. In the coming section of the tutorial, we will see how we can upload files in the spring boot application and also the implementation in detail for beginners. In this topic, we are going to learn about Spring boot file upload.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,130 ratings)

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

As we know, file upload is a mechanism to store text files or any other type of file to the server; in order to handle server should be ready to handle such requests. Let’s take a look at the syntax for the implementation of file upload in spring boot to see below;

@PostMapping("/your_rurl")
public retutn_type method_name(@RequestParam("name") MultipartFile obj) {
// logic goes here ..//
}

As you can see in the above syntax, we are using the MultipartFile object to handle the file upload in the spring boot application; inside this, we can define the logic for our method, and this object will contain the file we have uploaded from the client-side. Let’s take a look at the practice syntax for file upload; for better ideas, see below;

Example:

@PostMapping("/upload")
public void upload(@RequestParam("fileobj") MultipartFile fileobj) {
// logic goes here ..//
}

As you can see, we can define the method to handle the file upload in the spring boot application; it should be inside the controller class and will be a post mapping. In the coming section, we will see the steps required to make it work in the application.

How does the file upload function work in Spring boot?

In spring boot, as we have already known, we have to use multipart requests to support the binary and text file handling at the server-side. For this, we have to make use of the Multipart class, which requires configuration in the application.properties also. We can also upload multiple files at the same time but just need to be careful while handling it at the controller. The Multipart object will contain the list of files for us, which we can process further in the application. In this section, we will first see the steps required to make this happen in the spring boot application; let’s get started to see below;

1) First, we will go to the spring initializer and set up the spring boot project by entering all the details into the information, and we will add the necessary dependency. Click on generate a project, and it will give you zip, extract and import it into the favourite editor.

URL:

https://start.spring.io/

Output:

Spring boot file upload output 1

2) Once you download the project, do not forget to add the web dependency inside it, else it will not work from the rest-client tool to test it. For reference, below find the required dependency for the web see below;

Example:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

3) Now, we would require one more dependency, which is thymeleaf, add this dependency into your build file; for reference, please find the dependency below;

Example:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.4.3</version>
</dependency>

4) After adding all these things, we can now create the methods inside the controller which will handle the file upload in our spring boot application; let’s take a look at the controller level what changes we have to do see below;

Example:

import org.apache.coyote.Response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.security.Principal;
@RestController
@RequestMapping("/demo")
public class DemoController {
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file) {
String fileName  = file.getOriginalFilename();
int filelenth = file.getBytes().length;
return "File uploded successfully, " + "file name is :: "+ fileName + "and length is ::" + filelenth;
}
@GetMapping("/gettest/{test}")
public ResponseEntity<String> get(@PathVariable String test) {
return new ResponseEntity<>("I am get method " + test, HttpStatus.OK);
}
@PostMapping("/postMethod")
public ResponseEntity<String> post() {
return new ResponseEntity<>("I am post method " , HttpStatus.OK);
}
@DeleteMapping("/deleteMethod")
public ResponseEntity<String> delete() {
return new ResponseEntity<>("I am deleteMethod method " , HttpStatus.OK);
}
}

As you can see in the above line of code, we have used the Multipart object from the spring web dependency. To make it available in the class, we have to import the required packages at the top of the controller; we would require the below package for multipart in the controller see below;

Example:

import org.springframework.web.multipart.MultipartFile;

These packages should be in place; else, we will get the compile-time error in the controller, and to make it visible, we should have the web dependency in place, which we have discussed in step two.

Now we have to write some code at the service level, which will store the file in the server, creating one service class and writing the logic to save the file.

5) now, we have to make some changes to the application file where we will set the limit for the multipart data being uploaded and requested; we have a property defined in spring boot which we can use to set up this setting for reference; see below;

Example:

spring.servlet.multipart.max-file-size=500KB
spring.servlet.multipart.max-request-size=500KB

6) Now we should have our main class, which should be like below;

Example:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.*;
@SpringBootApplication
public class TradersApplication {
public static void main(String[] args)
{
SpringApplication.run(TradersApplication.class, args);
System.out.println("Application running in the dev mode !!");
}
}

6) Go to advance rest-client and try to hit the endpoint like below by making changes into content-type:

Output:

Spring boot file upload output 2

7) go to the body section and follow the below image, give the name of the variable and upload the file you want to upload like below;

Output:

output 3

8) after sending the request, you will get the following output in return;

Output:

output 4

Conclusion

To upload files in the spring boot application, we have to make use of multipart as we have discussed above, follow the above steps to make it work, and see the output. However, as we have seen, it is easy to use and also handle with a bit of o configuration is required.

Recommended Articles

This is a guide to Spring boot file upload. Here we discuss how we can upload files in the spring boot application and also the implementation in detail for beginners. You may also have a look at the following articles to learn more –

  1. Spring Boot Actuator
  2. Spring Boot Feature
  3. Spring Boot Annotations
  4. Spring Boot DevTools
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more