News Stay informed about the latest enterprise technology news and product updates.

A simple Spring Boot file upload example with Ajax

File uploads have challenged web developers in the past, as client side HTML provided limited facilities for integrating file selectors into the browser, and server-side processing of uploaded files was inconsistent across Java frameworks and often changed from one version of the API to the next. Fortunately, times have changed.

With HTML5 file input fields, integrating file selectors into a desktop or mobile browser is easy. And the MultipartFile class for Spring Boot file uploads makes processing an uploaded file and saving it to the server is relatively straight forward as well. In this Spring Boot file upload example, we will show you 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 file uploader

To use Spring Boot to upload files from the client to the server, follow these steps:

  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
  5. Send a response code to the client indicating the Spring file upload was successful

Spring Boot file upload controller

The code for the controller class which handles the Spring file upload is as follows.

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 greatly simplifies the Spring MVC code, as we don’t have to deal with forwards or results pages. We have one simple Spring Boot file upload controller on the server, and we have one simple Ajax based, HTML5 file uploader on the client.

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. Triggering the form submission through an Ajax call eliminates the need to wrap the HTML5 file input field with form tags, but it does introduce a few extra lines of JavaScript code. However, the payoff in terms user friendliness, along with the eliminated need to create any other HTML pages makes it worth it.

This following code needs to be saved 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 Sprint Boot file uploader

With the Spring controller coded and the HTML file saved to the templates directory, the application can be deployed and tested. 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 on GitHub.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close