Before save Image preview on upload

Learning with Earning

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;'}

In js file

$(function() {

  $(".preview_image").change(function() {

  $(".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.onload = function(e) {
        display: "block"
        display: "block"

#To remove image preview and image from file field.

removeURL = function(remove_button, input) {
    display: "none"
  return $(remove_button).css({
    display: "none"

Reference For Image Preview

View original post 107 more words


Leave a Reply

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

You are commenting using your 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