Read more

How to preview an image before uploading it

Dominik Schöler
May 09, 2016Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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
Posted by Dominik Schöler to makandra dev (2016-05-09 13:33)