Search⌘ K

File Upload

Explore how to implement file upload functionality in your Spring Boot and Thymeleaf application. Learn to map MultipartFile objects in forms, store avatar images in the database, and provide real-time previews for user avatars in the UI.

There are many applications that need file uploads in one form or another. Adding attachments to something or uploading an avatar for a user are two prime examples.

Implementing upload for avatars

Let’s add avatars for our users in the example application to show how file upload can be implemented. We start by adding an org.springframework.web.multipart.MultipartFile field to AbstractUserFormData:

Java
public class AbstractUserFormData {
...
private MultipartFile avatarFile;
public MultipartFile getAvatarFile() {
return avatarFile;
}
public void setAvatarFile(MultipartFile avatarFile) {
this.avatarFile = avatarFile;
}
}

This will allow us to map a selected file in an <input type="file"> from the <form> to the avatarFile field.

Create user form

Next, we’ll update CreateUserParameters to also add a MultipartFile field:

Java
public class CreateUserParameters {
...
private MultipartFile avatar;
@Nullable
public MultipartFile getAvatar() {
return avatar;
}
public void setAvatar(MultipartFile avatar) {
this.avatar = avatar;
}
}

When converting CreateUserFormData to CreateUserParameters, we’ll take the avatar field into account:

Java
public CreateUserParameters toParameters() {
CreateUserParameters parameters = new CreateUserParameters(new UserName(getFirstName(), getLastName()),
password,
getGender(),
getBirthday(),
new Email(getEmail()),
new PhoneNumber(getPhoneNumber()));
if (getAvatarFile() != null
&& !getAvatarFile().isEmpty()) { //<.>
parameters.setAvatar(getAvatarFile());
}
return parameters;
}

In line 10, if the form data has a valid MultipartFile, we’ll pass it to ...