In this brief guide, we shall learn how to upload a file in a Spring Boot web application using Ajax request. We will use jQuery on the client side for sending an asynchronously Ajax request.

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 an 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 the $.ajax() method:

$(document).ready(function () {
    // bind form submission 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 the Spring Boot controller that listens for an HTTP POST request at the /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 the 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 try to upload a larger file, you will encounter a MaxUploadSizeExceededException exception. But we can change this behavior by overriding multi-part properties in the 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.

Further Reading

Want to learn more about handling files in Spring Boot? Check out our in-depth guides:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.