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.
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]))
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.
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