Quantcast
Viewing all articles
Browse latest Browse all 168

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:

<form class="form" id="file-upload-form" 
  enctype="multipart/form-data">
  <div class="form-group">
    <label class="form-label required">
      Select File (multiple supported)
    </label>
    <input type="file" multiple class="form-control required" 
      id="uploaded-file" name="uploaded-file" />
  </div>
  <div>&nbsp;</div>
  <button class="btn btn-primary" type="submit">Upload</button>
</form>

<script>
  $(function (){
    $("#file-upload-form").submit(function (){
      $(this).ajaxSubmit({
        beforeSubmit: function (){
            return $('#file-upload-form').valid();
        },
        success: function(response){
            alert("Successfully uploaded the files");
        },
        error: function(){
            alert("Error occurred while uploading the files");
        },
        url: '/api/files/upload',
        type: 'POST'
      });
      return false;
    });
  });
</script>

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<MultipartFile> 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<MultipartFile> 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.


Viewing all articles
Browse latest Browse all 168

Trending Articles