Even though you now have an amazing default avatar, supporting actual avatars is a must have for any service, isn't it?
For today's project I suggest we implement a field that would allow user select an image and preview how it would look like as an avatar.
Custom Avatar Field: requirements and recipe
As a user I want to be able to pick an image, so that I could use it as my avatar.
The user story is intentionally vague: depending on the design choices the field might very different from one another.
On Dev.to it looks like this:
On LinkedIn it's much more complex:
You're free to choose the design and level of complexity, but some requirements should be met regardless.
Requirements
- Input should allow selection of only one image
- Preview avatar should be the exact size and shape as it would be used on the service
- Selected image should be scaled down to a required size before upload
- It should be possible to remove image and go back to the default avatar
Recipe
- Start with the file input field: setup all required validations
- Add a static preview avatar
- Update preview whenever a new file is selected
- Implement avatar removal logic
- Add the logic to scale the avatar down (keep it square though)
- Sprinkle with styles
- Ensure that input is still accessible
- Stare in awe at your creation!
Hints
In order to display a selected file one could use URL.createObjectURL(file)
and then use resulting url as usual.
Similarly to video thumbnails, you can use canvas to draw the selected file to scale it down.
Challenge: Storing avatars
Now that you have an input, it would make sense to implement the ability to upload those avatars somewhere so that others could see them.
Asset storage and delivery infrastructure would of course depend on the tech stack of each particular service, so let's implement only the upload part: you can store them locally in a key/value storage or simply in the file system.
We can't really use the actual name of selected file to store it though - because is multiple users are to upload avatar.jpg
- they'll simply override one another. A simple solution would be to calculate hash for each image and use that as a unique identifier. Also some images you might not even need to upload if they are already present ;-)
Share your creations and feedback and see you tomorrow!
Liked the idea a lot and would love to have it all year long?
Top comments (2)
Woot, another good one! You're on a roll. 🙌
Thank you! 🙏