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