Rails 7: Previewing Uploaded Images
Rails 7 isn't just a breath of fresh air for web app development - it's a full-blown revolution. jQuery's been shown the door, and now it's time to break free from front-end frameworks and mountains of JavaScript just to handle views.
I recently implemented an upload feature in a Hotwire and Stimulus-powered app. I'm over the moon that despite having a fairly complex UI, there's barely a dozen lines of JS in the entire thing.
The Challenge: Image Preview Before Upload
I faced the task of creating an image preview before form submission. Here's the scenario: user clicks "Choose file", selects an image, and boom - it automatically appears in the preview area.
Here's how I cracked it using Stimulus, which I'm growing fond of due to its simplicity.
For this example, I've whipped up a super stripped-down view:
I've created a Stimulus controller called ImageUploadPreview
.
Two targets were established:
input
: the file input fieldpreview
: the img
tag for displaying the chosen image previewThe setImagePreview
function contains all the logic. Here's the breakdown:
Here's the step-by-step breakdown:
reader.onload
- an event triggered when the selected image is loaded in the readersrc
to the reader's resultThat's it - magic complete.
Now, just hook up the controller, targets, and action to the view elements.
data-controller
is set on the container for both input and previewfile_field_tag
and image_tag
are marked as input
and preview
targetssetImagePreview
action is attached to the inputThe final functionality looks like this:
