Enterprise Java

Uploading files in Spring Boot application

Uploading files is one of the most common operations in a web application. In this article we will look at how to upload file from an HTML page and copy it to the file system on the server.

Creating a HTML form with file upload option

The below HTML code and its corresponding Javascript code creates the HTML form and binds the form with the API created in your Spring Boot application:

 

enctype="multipart/form-data" is an important attribute which should be present in the <form> that deals with uploading files.

In the above HTML I am using jQuery Validation and jQuery Form Plugin to handle form validations as well as submitting them asynchronously.

Server side code to handle file uploads

There will be two components in the server side:

  • API Controller to receive the uploaded files.
  • Code to copy the files to File System or any other file storage location.

API Controller

Below is the code for the API to receive the uploaded files:

@PostMapping("/upload")
public ResponseEntity handleFileUpload(
  @RequestParam("uploaded-file") List uploadedFiles){
   
  log.debug("Uploaded files size : {}", uploadedFiles.size());
   
  fileService.copyFile(uploadedFiles);
   
  return ResponseEntity.ok().build();

It is important to note that the value passed to the annotation @RequestParam should match the value of the name attribute of the <input type="file" /> HTML element.

Let us look at the copyFile method implementation:

@Service
public class FileService {
  @Value("${app.document-root}")String documentRoot;
 
  public void copyFile(List uploadedFiles) throws IOException{
 
    try {
      Path docRootPath = Path.of(documentRoot);
      if ( !Files.exists(docRootPath)){
        Files.createDirectory(docRootPath);
      }
      for (MultipartFile multipartFile : uploadedFiles) {
        String fileName = multipartFile.getOriginalFilename();
        multipartFile.transferTo(Path.of(documentRoot, fileName));
      }
    } catch (IOException e) {
      log.error("Error occurred while copying file", e);
      throw e;
    }
  }
}

MultipartFile is an interface provided by Spring framework for working with uploaded files. By default the uploaded file is wrapped in StandardMultipartFile which is one of the implementations of MultipartFile. We make use of the method transferTo to copy the uploaded file to our desired destination on the file system.

The property app.document-root is defined in the file application.properties

Properties to configure file upload size limits

Spring boot provides certain properties to configure the size limit of the file uploaded:

  • spring.servlet.multipart.max-file-size – this property controls the maxmium size of the file uploaded
  • spring.servlet.multipart.max-request-size – this property controls the maximum size of the request (which includes the total size of all the files uploaded).

The complete application can be found in the GitHub project here.

In next set of posts we will see how to make use of Apache Commons File library to handle file uploads and also how to copy to other storage services like S3.

Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: Uploading files in Spring Boot application

Opinions expressed by Java Code Geeks contributors are their own.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button