How to preview an image before uploading it

Updated . Posted . Visible to the public.

When building a form with a file select field, you may want to offer your users a live preview before they upload the file to the server.

HTML5 via jQuery

Luckily, HTML5 has simple support for this. Just create an object URL Show archive.org snapshot and set it on an <img> tag's src attribute:

$('img').attr('src', URL.createObjectURL(this.files[0]))

Unpoly Compiler

As an Unpoly compiler Show archive.org snapshot , it looks like this:

up.compiler '[image_preview]', (element, img_selector) ->
  img = $(img_selector)

  element.on 'change', ->
    blobURL = URL.createObjectURL(this.files[0])
    img.attr 'src', blobURL

Use it in a form like this:

= form.label :image do
  = form.file_field :image, image_preview: true, 'up-data': '.image-preview'.to_json
    Choose image

= image_tag image, class: 'image-preview'

The image_tag will either contain an existing image (rendered by Rails) or be overwritten by Unpoly with an image preview.

Testing

Here's a Cucumber step to check the existence of a preview image:

Then /^I should see an image preview$/ do
  page.execute_script(<<-JS).should be true
    $('img[src^=blob]').length > 0
  JS
end
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-05-09 11:33)