Spring Boot file upload example with Ajax

Web developers have never had it easy to upload files, on both the client- and server-side. Limited facilities to integrate file selectors into the browser have plagued client-side HTML. Server-side file uploads suffered from an inconsistent process across Java frameworks that often changed versions of the API.

Fortunately, times have changed. With HTML5 file input fields, it’s now easy to integrate file selectors into a desktop or mobile browser. The Multipart File class for Spring Boot file uploads makes processing and saving uploaded files to the server relatively straightforward as well.

In this Spring Boot file upload example we demonstrate how easy it is to move a file from the client browser to a folder on the server — all asynchronously — and with a minimal amount of code.

Spring Boot file uploader

Follow these five steps to use Spring Boot to upload files from the client to the server:

  1. Create a Spring Boot application and include the Spring Web facilities;
  2. Create a Spring @Controller class;
  3. Add a method to the controller class which takes Spring’s MultipartFile as an argument;
  4. Save the uploaded file to a directory on the server; and
  5. Send a response code to the client indicating the Spring file upload was successful.

Spring Boot file upload controller

Developers should use the following code for the controller class, which handles the Spring file upload:

package com.example.demo;

import java.io.File;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class SpringFileUploadController {

  @GetMapping("/index")
  public String hello() {
    return "uploader";
  }

  @PostMapping("/upload") 
  public ResponseEntity<?> handleFileUpload( @RequestParam("file") MultipartFile file ) {

    String fileName = file.getOriginalFilename();
    try {
      file.transferTo( new File("C:\\upload\\" + fileName));
    } catch (Exception e) {
      return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    } 
    return ResponseEntity.ok("File uploaded successfully.");
  }

}

The controller code assumes an Ajax-based invocation, so only status codes are returned to the browser. This simplifies the Spring MVC code, which means we don’t have to deal with forwards or results pages. We have one Spring Boot file upload controller on the server, and one Ajax-based HTML5 file uploader on the client.

More file upload options

I put together a bunch of file upload tutorials. Pick your technology and get uploading!

Uploading files to the server need not be a problem.

Ajax and Spring file uploader

The easiest way to add file upload functionality to a web page is to use the HTML5 file input tags. A developer triggers the form submission through an Ajax call, which eliminates the need to wrap the HTML5 file input field with form tags. That also introduces a few extra lines of JavaScript code, but the payoffs — user friendliness, and no need to create any other HTML pages — are worth it.

Developers should save the following code to a file named uploader.html in the templates directory of the Spring Boot file upload example project.

<html xmlns:th="http://www.thymeleaf.org">
<head> 
<title> Ajax Spring File Upload Example </title> 
</head> 
<body>

<!-- HTML5 Input Form Elements -->
<input id="fileupload" type="file" name="fileupload" /> 
<button id="upload-button" onclick="uploadFile()"> Upload </button>

<!-- Ajax JavaScript File Upload to Spring Boot Logic -->
<script>
async function uploadFile() {
  let formData = new FormData(); 
  formData.append("file", fileupload.files[0]);
  let response = await fetch('/upload', {
    method: "POST", 
    body: formData
  }); 

  if (response.status == 200) {
    alert("File successfully uploaded.");
  }
}
</script>

</body> 
</html>

Run the Ajax Spring Boot file uploader

With the Spring controller coded and the HTML file saved to the templates directory, a developer can deploy and test the application. When the application runs, the URL to bring up the HTML5 file upload form in the browser is:

http://localhost:8080/index

The result is an Ajax-based Spring Boot file upload that persistently saves files uploaded to the server from the client’s browser.

PHP file upload example

The Spring Boot file upload controller will persistently save images and other files sent to the server from a the client’s browser.

The source code for this Spring file upload example is available GitHub.

SearchAppArchitecture
SearchSoftwareQuality
SearchCloudComputing
SearchSecurity
SearchAWS
Close