File upload in a Spring Boot application

To configure file upload in a Spring application, you need to perform the following steps:


  1. Add the necessary dependencies to your project. In your project's pom.xml (if using Maven) or build.gradle (if using Gradle), include the following dependencies:

For Maven:

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


For Gradle:

implementation 'org.springframework.boot:spring-boot-starter-web'
  1. Configure the necessary beans in your Spring configuration file (usually application.properties or application.yml).

For application.properties:

# Maximum file size (in bytes) that can be uploaded
spring.servlet.multipart.max-file-size=10MB
# Maximum request size (in bytes) allowed for multipart/form-data
spring.servlet.multipart.max-request-size=10MB


For application.yml:

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

  1. In your controller class, define a method to handle the file upload request. Use the @RequestParam annotation to bind the uploaded file to a parameter.

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class FileUploadController {
    
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        // Process the uploaded file
        // You can access the file's content through file.getInputStream()
        // Perform your desired operations with the file
        
        return "File uploaded successfully!";
    }
}

  1. Create a form in your HTML file for the file upload. Ensure that the form's enctype attribute is set to "multipart/form-data".

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>


In this example, the form sends a POST request to /upload, and the selected file is bound to the file parameter in the handleFileUpload method of the FileUploadController.


These steps configure file upload in a Spring application. Remember to adjust the file size limits and other configuration properties according to your requirements.