File Upload

Learn how to implement the file upload feature in the application.

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:

Press + to interact
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:

Press + to interact
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:

Press + to interact
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 ...