In this short guide, we will learn how to upload a file in Spring Boot web application using Ajax request. We will be use jQuery on client-side for sending asynchronously Ajax requests.

HTML Form

Let's create a simple HTML form that enables users to select a file for upload:

<form id="file-upload-form">
    <label for="file-upload-input">Select file to upload</label>
    <input type="file" id="file-upload-input" name="file">
    <button type="submit">Start Upload</button>
</form>

jQuery Ajax Request

For Ajax request, we will bind the onsubmit event for the form element that will be triggered when the form is submitted. Here is a jQuery code that listens for form submission event and sends the file to the server using $.ajax() method:

$(document).ready(function () {
    // bind form submit event
    $("#file-upload-form").on("submit", function (e) {

        // cancel the default behavior
        e.preventDefault();

        // use $.ajax() to upload file
        $.ajax({
            url: "/file-upload",
            type: "POST",
            data: new FormData(this),
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
            cache: false,
            success: function (res) {
                console.log(res);
            },
            error: function (err) {
                console.error(err);
            }
        });
    });
});

Spring Boot Controller

Finally, create a new method in Spring Boot controller that listens for an HTTP POST request at /file-upload end-point. This method handles the file upload request and saves the file in a local directory:

@PostMapping("/file-upload")
@ResponseBody
public ResponseEntity<String> fileUpload(MultipartFile file) {
    try {

        // upload directory - change it to your own
        String UPLOAD_DIR = "/opt/uploads";

        // create a path from file name
        Path path = Paths.get(UPLOAD_DIR, file.getOriginalFilename());

        // save the file to `UPLOAD_DIR`
        // make sure you have permission to write
        Files.write(path, file.getBytes());
    }
    catch (Exception ex) {
        ex.printStackTrace();
        return new ResponseEntity<>("Invalid file format!!", HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>("File uploaded!!", HttpStatus.OK);
}

Maximum File Size

By default, Spring Boot only allows a maximum file size of 1MB. If you will try to upload a larger file, you will encounter a MaxUploadSizeExceededException exception. But we can change this behavior by overriding multi-part properties in application.properties file:

# max file size - default 1MB
spring.servlet.multipart.max-file-size=25MB
# max request size - default 10MB
spring.servlet.multipart.max-request-size=50MB

Now we can upload a file that can be larger than 1MB without worrying about any error on the server. It also increases the maximum request size to 50MB.

Want to learn more about handling files in Spring Boot? Checkout our in-depth guide on uploading files in Spring Boot.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)


Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.