Before save Image preview on upload

Learning with Earning

Note:
f -> form-for object/ FormBuilder Object, incase if you wants to use image preview for fields_for then pass fields_for object to image_preview helper method

In html.erb file

<%= image_preview(f) %>

In helper file


def image_preview(f)
	    url, style =  f.object.image.present? ?  [f.object.image.url(:thumb), ''] : ['#','display:none;']
	    content_tag(:div, nil) do
		    concat image_tag url , {id: 'img_prev', style: style}
		    concat ''.html_safe
		    concat  f.button 'Remove', {type: 'button', class: 'remove_image', style:'display:none;'}
	    end
	end

In js file


$(function() {

  $(".preview_image").change(function() {
    readURL(this);
  });

  $(".remove_image").click(function() {
    removeURL(this, $(".preview_image"));
  });
});

#To show image preview
readURL = function(input) {
  var reader;
  if (input.files && input.files[0]) {
    reader = new FileReader();
    reader.readAsDataURL(input.files[0]);
    reader.onload = function(e) {
      $("#img_prev").attr("src", e.target.result)
      .width(200).height(150)
      .css({
        display: "block"
      });
      $('.remove_image').css({
        display: "block"
      });
    };
  }
};

#To remove image preview and image from file field.

removeURL = function(remove_button, input) {
  $(input).val('');
  $("#img_prev").css({
    display: "none"
  });
  return $(remove_button).css({
    display: "none"
  });
};

Reference For Image Preview

View original post 107 more words

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s