Stimulus - Image Upload Previews with `URL.createObjectURL`

Create client-side previews of files using URL.createObjectURL

View Solution on Patreon
Stimulus - Image Upload Previews with `URL.createObjectURL`

Premise

One of the largest UX improvements you can achieve regarding file (specifically, media) uploads is to display previews of what’s getting uploaded early on. What’s the earliest point to do this? Well, before the upload even starts, because JavaScript has a way of creating blob URLs representing an object in memory.

Starting Point

We have a simple file upload field that accepts multiple images:

https://stackblitz.com/edit/stimulus-image-upload-previews?file=index.html%3AL41

There’s also a template containing a list item to act as a preview:

https://stackblitz.com/edit/stimulus-image-upload-previews?file=index.html%3AL49

Finally, there’s an unordered list that will contain the previews:

https://stackblitz.com/edit/stimulus-image-upload-previews?file=index.html%3AL61

Those are all wrapped in a <div> that is appointed to the file-preview Stimulus controller.

Challenge

Using the File API, create Blob URLs that represent the uploaded images and append each of them to the previewsTarget:

For this you’ll have to clone the template, fill in the placeholders (file name and size with composite’s fill function), and append it to the list.

Hint: Look at this guide.

Here’s a preview of the result:

Displaying image previews when starting an upload

Teasers

  • How could you re-use these previews with the actual uploaded images?

More from

Stimulus - Video Progress Tracker with LocalStorage
29 October 2024

Store ephemeral user state like video playback progress in localStorage

Stimulus - Removing Markers from a Wavesurfer Element
30 July 2024

Use Stimulus value callbacks to interact with a wavesurfer element and remove markers.

Stimulus - Adding Markers to a Wavesurfer Element
02 July 2024

Use Stimulus value callbacks to interact with a wavesurfer element and add markers.

Cookies
essential