Uploading Files in Spring Boot

  • Last updated Apr 25, 2024

In this example, we will show you how to upload both single and multiple files including the ability to receive additional data along with the files in Spring Boot by using the MultipartFile interface from the org.springframework.web.multipart package of Spring Framework.

Here's an example code snippet of a Spring Boot controller class that handles file uploads:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.dto.FileUploadResponse;

@RestController
@RequestMapping(value = "/files")
public class FileUploadController {

  private final String FILE_LOCATION = "/home/files/";

  @PostMapping(path = "/upload-file")
  public @ResponseBody FileUploadResponse uploadSingleFile(MultipartFile multipleFile, Map params) {

     /* We can receive other data with multipart file */
     String firstName = params.get("firstName");
     String lastName = params.get("lastName");

     String filename = multipleFile.getOriginalFilename();

     // Replace space in filename with underscore
     filename = filename.replaceAll("\\s", "_");

     // Location to save the file
     String fileUploadLocation = FILE_LOCATION + filename;

     File file = new File(fileUploadLocation);

     try {
	  if (file.createNewFile()) {
		try (FileOutputStream fos = new FileOutputStream(file)) {
		      fos.write(multipleFile.getBytes());
	        }
          }
     } catch (IOException e) {
	  e.printStackTrace();
     }

     FileUploadResponse response = new FileUploadResponse();
     response.setFileUrl(fileUploadLocation);
     return response;
  }

  @PostMapping(path = "/upload-files")
  public @ResponseBody List<FileUploadResponse> uploadMultipleFiles(MultipartFile[] multipleFiles, Map params) {

    List<FileUploadResponse>
         fileUploadListResponse = new ArrayList<>(); /* We can receive other data with multipart files. */ String firstName = params.get("firstName"); String lastName = params.get("lastName"); /* multiple multipart files using for loop */ for (MultipartFile multipleFile : multipleFiles) { String filename = multipleFile.getOriginalFilename(); // Replace space in filename with underscore filename = filename.replaceAll("\\s", "_"); // Location to save the file String fileUploadLocation = FILE_LOCATION + filename; File file = new File(fileUploadLocation); try { if (file.createNewFile()) { try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(multipleFile.getBytes()); } } } catch (IOException e) { e.printStackTrace(); } FileUploadResponse response = new FileUploadResponse(); response.setFileUrl(fileUploadLocation); fileUploadListResponse.add(response); } return fileUploadListResponse; } }

Here's the class representing the response in the given example controller:

public class FileUploadResponse {

  private String fileUrl;

  public String getFileUrl() {
     return fileUrl;
  }

  public void setFileUrl(String fileUrl) {
     this.fileUrl = fileUrl;
  }

}

Here's an explanation of the above code:

  1. The FileUploadController is a controller class that is annotated with @RestController and @RequestMapping to indicate that it handles HTTP requests and produces JSON responses. It defines the base URL mapping for all the endpoints in the controller.
  2. The FILE_LOCATION variable represents the directory where uploaded files will be saved.
  3. The uploadSingleFile method handles the upload of a single file. It takes MultipartFile multipleFile and Map params as parameters, representing the uploaded file and additional parameters sent with the request, respectively. A FileUploadResponse object is created, the fileUrl property is set to the file upload location, and the response object is returned.
  4. The uploadMultipleFiles method handles multiple file uploads using an array of MultipartFile objects. It iterates through the array, performs similar file handling operations for each file, and adds the corresponding FileUploadResponse objects to a list. The list of FileUploadResponse objects is returned as the response.
  5. Inside both the methods, firstName and lastName are extracted from the params map, demonstrating the ability to receive additional data along with the file upload.
  6. The original filename of the uploaded file is obtained using multipleFile.getOriginalFilename(). Spaces in the filename are replaced with underscores.
  7. The file upload location is constructed by appending the filename to the FILE_LOCATION.
  8. A File object is created with the file upload location. The file is created using file.createNewFile(), and if successful, the file contents are written using a FileOutputStream.
  9. Exceptions during file handling are caught, and the stack trace is printed to the console.

Both APIs demonstrate how to handle file uploads in Spring Boot. They allow clients to send files along with additional data, process the uploaded files, and provide appropriate responses with file URLs or other relevant information. These APIs provide a foundation for implementing file upload functionality in Spring Boot applications.