Profile Image Uploads: The Spring Parts

We gave you a quick overview of the Profile Image Upload function in our last post. In this post we’re going to get into some of the behind-the-scenes Spring elements. We’ll cover

  • File Uploading with Spring MVC and Thymeleaf
  • Using Spring Validation with a DTO object to validate file upload properties
  • How we’re determining if the user has a custom profile image
  • Creating and saving the image and its thumbnail
  • Handling the profile image of Social Users with Spring’s UserConnection object

File Uploading with Spring MVC

We’ll jump right to the Controller Method handling our MultipartFile {post} action. Our first method parameter is a @Valid ProfileImageDTO object which we’ll use to validate the uploaded file properties.

ProfileImageDTO

Our ProfileImageDTO object is pretty simple, but its enough to use with Spring Validation.

Below is our Spring ProfileImageValidator. Notice how we’re using a @Value annotation to set our ImageMaxSize property.

Here’s the result of a file which is too large.

One thing to mention when using a DTO Container for our MultipartFile is that it needs to be passed from the form, so we first pass the ProfileImageDTO Model object to our Profile page…

…for use as our Thymeleaf MultipartFile Upload form th:object.

Determining if the user has a custom profile image is straightforward with a new hasAvatar Property added to the User Model, shown here in the first column of the User table. The new user_key property identifying the image file name is in the second column.

The logic then for establishing the image Url is pretty simple when retrieving the User Image Url.

What To Do With Social Users

Our app supports Social Users who sign-up through OAuth Providers like Facebook. We could display their Profile Images with the Spring UserConnection object I blogged about here, but we want to use that profile image as well as give them the ability to create a site-specific profile image if they wish. We’ll start by making a local copy of their Social Image from their Provider. This will also allow us to use the same Profile Image display logic for all users, Social Users and those with Local Accounts.

The code below is from our Spring Social MVC method where we create the local User Account. You can see how we’re using our UserConnection object to retrieve the Provider Profile Image Url and pass it to our Image Processing function.

Saving the Images

We’ll be using Thumbnailator to process and save our image to 600×600 and 32×32 size.

There are other interesting Spring issues with the Profile Image Update. We accessed the Spring Context from a Java Class and updated the Authenticated User properties in the current Session, as two such examples. Both are pretty cool which we’ll no doubt cover in a  future post.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.