Spring Boot File Handling

Spring Boot File Handling with Examples

In this article, I am going to discuss Spring Boot File Handling with Examples. Please read our previous article where we discussed Spring Boot Servlet Filters.

What is File Handling?

File handling is the method to handle files through a web server. This includes uploading and downloading files. In this exercise, we shall have three aspects in our file handling:

  1. Uploading files to the application server
  2. Downloading files from the application server
  3. List files that are present in the application server
How to Implement File Handling in Spring Boot?

For this project, we shall create one extra class, which will function as the REST controller.

Step 1: Create a new project using Spring Initializr in VS Code. Remember to include the spring-boot-starter-web dependency. Please check our Spring Boot Setup article.

Step 2: Modify the application.properties file in src/main/resources directory to configure the required parameters:

How to Implement File Handling in Spring Boot?

  • spring.servlet.multipart.enabled=true enables multipart files to be uploaded/downloaded to/from the application
  • spring.servlet.multipart.max-file-size=10MB sets the maximum size of the upload file
  • spring.servlet.multipart.max-request-size=10MB sets the maximum size of the download file

Step 3: Create a file called FileController.java in the src/main/java/com/dotnet/filehandling directory.

Step 4: Import the following packages into the newly created class:

How to Implement File Handling in Spring Boot?

Step 5: Add the @RestController annotation to the class.

Step 6: Write a function to facilitate the file uploads:

How to Implement File Handling in Spring Boot?

In this function, the following steps are performed:

  1. The file path is obtained.
  2. A file output stream is created. A file can be written by means of this stream.
  3. The file is written to the server.
  4. The file upload status is updated.

Also, note that the code is in a try-catch block to handle a condition of failure when uploading the file to the server.

Step 7: Write a function to return the list of files:

Spring Boot File Handling with Examples

In this function, the following steps are performed:

  1. The file path is obtained.
  2. The files present in the directory are listed.

Step 8: Write a function to facilitate the file downloads:

Spring Boot File Handling with Examples

In this function, the following steps are performed:

  1. The file path is obtained.
  2. The file request which was sent by the client is read.
  3. If the file is not present in the application folder, an error message is returned.
  4. Otherwise, the file is sent to the client.

Step 9: Save and compile the program. Ensure the compilation is successful.

Spring Boot File Handling with Examples

Step 10: Create an Uploads directory in the file structure. This is where the uploaded files shall appear.

Spring Boot File Handling

Step 11: Open Postman and send a POST request to the application. Use the http://localhost:8080/upload URL. Once you enter the key as a file, a small dropdown shall open beside the key. Upon clicking on the dropdown, you shall be treated with two options, ‘Text’ & ‘File’. Select the ‘File’ option.

Spring Boot File Handling

The following message appears in the Postman window:

Spring Boot File Handling

The file appears in the Uploads directory:

Spring Boot File Handling

Step 12: Send a GET request to the application via Postman. Use the http://localhost:8080/getfiles URL. The following message appears:

Spring Boot File Handling

As can be seen, the file we uploaded in Step 11 is visible. Congratulations! You have now learned how to implement file handling in Spring Boot!

The Complete Example Code
FileController.java
package com.dotnet.filehandling;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;

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;

@RestController
public class FileController
{
    //Method to upload a file
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String uploadFile(@RequestParam("file") MultipartFile file)
    {
        //Set the file path
        String filePath = System.getProperty("user.dir") + "/Uploads" + File.separator + file.getOriginalFilename();
        String fileUploadStatus;

        try
        {
            FileOutputStream fOut = new FileOutputStream(filePath);
            fOut.write(file.getBytes());
            fOut.close();
            fileUploadStatus = "File uploaded successfully!";
        }

        catch (Exception e)
        {
            e.printStackTrace();
            fileUploadStatus = "Error: " + e;
        }

        return fileUploadStatus;
    }
    
    //Method to list files present in the server
    @RequestMapping(value = "/getfiles", method = RequestMethod.GET)
    public String[] getFiles()
    {
        String folderPath = System.getProperty("user.dir") + "/Uploads";
        File directory = new File(folderPath);

        //list all the files present in this directory
        String[] files = directory.list();
        return files;
    }

    @RequestMapping(value = "/download/{path:.+}", method = RequestMethod.GET)
    public ResponseEntity downloadFile (@PathVariable("path") String fileName) throws FileNotFoundException
    {
        String fileUploadPath = System.getProperty("user.dir") + fileName;
        String[] fileList = this.getFiles();
        
        //Check if the file is present
        if (!Arrays.asList(fileList).contains(fileName))
            return new ResponseEntity("File Not Found!", HttpStatus.NOT_FOUND);
        
        String filePath = fileUploadPath + File.separator + fileName;
        File file = new File(filePath);
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        HttpHeaders headers = new HttpHeaders();

        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);
    }
}
FilehandlingApplication.java
package com.dotnet.filehandling;

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

@SpringBootApplication
public class FilehandlingApplication {

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

}

In the next article, I am going to discuss Spring Boot Service Components with Examples. Here, in this article, I try to explain Spring Boot File Handling with Examples. I hope you enjoy this Spring Boot File Handling article.

Leave a Reply

Your email address will not be published. Required fields are marked *