# How to upload a file with Ajax in Spring Boot

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 3, 2019, updated Sep 25, 2022. Topics: Spring Boot, Ajax.
Canonical URL: https://attacomsian.com/blog/spring-boot-file-upload-with-ajax

> A short guide for uploading a file in Spring Boot web application through asynchronous Ajax request.

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:

```html
<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:

```javascript
$(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:

```java
@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: 

```properties
# 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:

* [Uploading and downloading files using Spring Boot REST API](https://attacomsian.com/blog/uploading-files-spring-boot)
* [Spring Boot and Thymeleaf File Upload Example](https://attacomsian.com/blog/spring-boot-thymeleaf-file-upload)
