Spring Boot - File Handling

Last Updated : 14 Mar, 2026

File handling in Spring Boot refers to the process of uploading, storing, retrieving, and downloading files through REST APIs in a web application. Spring Boot provides built-in support for file upload using MultipartFile and simplifies file operations through its integration with the Spring Web module.

  • Enables file upload and download functionality in web applications using REST APIs.
  • Uses MultipartFile to handle files received through multipart/form-data requests.
  • Allows applications to store files on the server and retrieve them when required.

Implementation of the Application

Now, let us implement a Spring Boot application to demonstrate file upload and download functionality step by step.

Step 1: Create a Spring Boot Project

Generate a project using Spring Initializr and fill in the details:

  • Project: Maven
  • Language: Java
  • Spring Boot Version: Latest stable version
  • Group: com.example
  • Artifact: springboot-file-handling
  • Packaging: Jar
  • Java Version: 17 (or higher)
  • Dependencies: Spring Web

Click Generate to download the starter project.

Step 2: Configure File Upload Properties

Add the following configuration in application.properties to enable multipart file uploads.

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Explanation:

  • spring.servlet.multipart.enabled
    Enables multipart file upload functionality.
  • spring.servlet.multipart.max-file-size
    Specifies the maximum allowed size for an uploaded file.
  • spring.servlet.multipart.max-request-size
    Specifies the maximum size allowed for a multipart request.

Step 3: Create the Main Class

Create the main class to run the Spring Boot application.

Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootFileHandlingApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootFileHandlingApplication.class, args);
    }

}

Step 4: Create the Controller Class

Create a FileController class to handle file upload, download, and listing operations.

Java
// Java Program to Create Rest Controller 
// that Defines various API for file handling
package com.SpringBootFileHandling.controller;

// Importing required classes
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

// Annotation
@RestController
public class FileController {
    
    // Uploading a file
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file") MultipartFile file){

        // Setting up the path of the file
        String filePath = System.getProperty("user.dir") + "/Uploads" + File.separator + file.getOriginalFilename();
        String fileUploadStatus;
        
        // Try block to check exceptions
        try {
            
            // Creating an object of FileOutputStream class  
            FileOutputStream fout = new FileOutputStream(filePath);
            fout.write(file.getBytes());
            
            // Closing the connection 
            fout.close();
            fileUploadStatus = "File Uploaded Successfully";
            
        } 
      
        // Catch block to handle exceptions
        catch (Exception e) {
            e.printStackTrace();
            fileUploadStatus =  "Error in uploading file: " + e;
        }
        return fileUploadStatus;
    }
    
    // Getting list of filenames that have been uploaded
    @RequestMapping(value = "/getFiles", method = RequestMethod.GET)
    public String[] getFiles()
    {
        String folderPath = System.getProperty("user.dir") +"/Uploads";
        
          // Creating a new File instance
        File directory= new File(folderPath);
        
        // list() method returns an array of strings 
          // naming the files and directories 
          // in the directory denoted by this abstract pathname
        String[] filenames = directory.list();
        
        // returning the list of filenames
        return filenames;
        
    }
    
    // Downloading a file
    @RequestMapping(value = "/download/{path:.+}", method = RequestMethod.GET)
    public ResponseEntity downloadFile(@PathVariable("path") String filename) throws FileNotFoundException {
    
        // Checking whether the file requested for download exists or not
        String fileUploadpath = System.getProperty("user.dir") +"/Uploads";
        String[] filenames = this.getFiles();
        boolean contains = Arrays.asList(filenames).contains(filename);
        if(!contains) {
            return new ResponseEntity("FIle Not Found",HttpStatus.NOT_FOUND);
        }
        
        // Setting up the filepath
        String filePath = fileUploadpath+File.separator+filename;
        
        // Creating new file instance
        File file= new File(filePath);
        
        // Creating a new InputStreamResource object
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        
        // Creating a new instance of HttpHeaders Object
        HttpHeaders headers = new HttpHeaders();
        
        // Setting up values for contentType and headerValue
        String contentType = "application/octet-stream";
        String headerValue = "attachment; filename=\"" + resource.getFilename() + "\"";
             
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                .body(resource); 
        
    }
}

Step 5: Run the Application

Run the main class.
The Spring Boot application will start on:

http://localhost:8080

Step 6: Test the APIs Using Postman

1. Upload File API

URL

POST http://localhost:8080/upload

In order to upload a file we need to hit http://localhost:8080/upload in Postman with form data as shown below:

Upload API in Postman

On Successful upload of the file, we can see the file in the Uploads folder as below:

File Uploaded in Uploads Folder

2. Get list of Files API

We need to hit http://localhost:8080/getFiles in postman to get a list of filenames that have been uploaded.

URL

GET http://localhost:8080/getFiles


getFiles API in Postman


3. Download File API

URL

GET http://localhost:8080/download/{filename}

In order to download a file we need to hit http://localhost:8080/download/{filename} in postman as shown below.

Download API in Postman

The file can be downloaded in Postman using Save Response → Save to a File, or directly from the browser using the download URL. If the file does not exist, the API returns "File Not Found" with HTTP 404.

File Not Found Output in Postman
Comment