Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails+javascript - image preview before upload

I want to show an image preview before upload, for that I am using the code given below.

It works with firefox, but doesn't work with IE8

<%= image_tag @image, :id=>"preview-photo" %>
<%= file_field 'image','photo', :onchange => "preview(this);" %>

function preview(this) {
  document.getElementById("preview-photo").src = this.value;
  return;
}

Is there any solution to preview the image in IE8 and other browsers?

like image 350
lamrin Avatar asked Apr 08 '11 10:04

lamrin


1 Answers

In ERB: Take input, and give it a class name and dynamic id, and also make a image tag with dyanamic id where you will show the preview pic.

<%= f.file_field :photo, :class => 'photo_upload', :id => "image_#{image.id}" %>  
<%= image_tag("preview.png", :id => "image_#{image.id}_medium") %>

In JAVASCRIPT:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();            
      reader.onload = function (e) {
          $(document.getElementById(input.id + "_medium")).attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$(".photo_upload").change(function(){
    readURL(this);
});
like image 170
Nitesh Avatar answered Sep 29 '22 21:09

Nitesh