Rails 7: Previewing Uploaded Images

12 marca 2025

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 field
  • preview: the img tag for displaying the chosen image preview
  • The setImagePreview function contains all the logic. Here's the breakdown:

    Here's the step-by-step breakdown:

  • Check if any file was selected
  • Create a FileReader instance to fetch the chosen image's location
  • Set up a callback and attach it to reader.onload - an event triggered when the selected image is loaded in the reader
  • In the callback, set the preview's src to the reader's result
  • Load the image using the reader to get its URL
  • That'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 preview
  • file_field_tag and image_tag are marked as input and preview targets
  • The setImagePreview action is attached to the input
  • The final functionality looks like this:

    image