Storage with Profile Image

Allow users to upload a profile image to your app.

v1.8.3 v1.7.12
Level: Easy
10
248
1

Update Accounts context

Add helper functions for changing user profile information:

Update Scope to preload profile image

Modify for_user/1 to preload the user's profile image association. This ensures the profile image is available throughout the application wherever the current scope is used, without requiring additional queries.

Update User schema

Add new fields to the User schema:

Add a profile_changeset/2 function that casts and validates the name field with a maximum length of 50 characters.

Add update_profile_image_multi/2 which handles the complexity of updating a user's profile image:

This multi ensures that old profile images are cleaned up when replaced.

Update Storage context

Add a direct_upload/2 function for uploading files directly rather than using external (presigned) uploads. This is useful for server-side image processing before upload.

The function:

Image processing tools

The ImageTools module provides functions for resizing images using FFmpeg:

Images are cropped to square from the center before scaling, ensuring consistent profile image dimensions regardless of the original aspect ratio.

Update Object schema

Extend insert_assocs_multi/3 to handle the :user_profile_image option, which calls User.update_profile_image_multi/2 to associate the new image with the user.

Add a delete_multi/2 function that marks an object as deleted within a multi transaction. This is used by the profile image update flow to clean up old images.

Profile image upload component

Add a profile_image_upload/1 component that renders an upload input styled as a profile image editor:

The component accepts slots for :preview (shown during upload) and :inner_block (shown when no upload is in progress).

User profile component

Create a user_profile/1 component that displays a user's profile image:

This component can be reused throughout the application wherever user avatars are needed.

Update Settings LiveView

Extend the settings page with profile editing:

The update_profile handler:

Migration

Alters the users table to add: