Upload image as Base64 by Ajax with image preview:
jQuery:
$(document).on("change", "#company_background_image", function(){
var output = this;
output.src = URL.createObjectURL(event.target.files[0]);
$(".img-container img").attr("src",output.src);
if ($(".img-preview.preview-lg img").size()!=0){
$(".img-preview.preview-lg img").attr("src",output.src);
}
$("#img-cropp").modal("show");
})
Controller:
def image_cropping
begin
Base64.decode64(img=params["crop-img"])
#getting only the string leaving out the data/<format>
img = file_decode(img.split(',')[1], @company.background_image.filename)
@company.background_image = img
@company.save
rescue Exception => e
#Returning if its not a base64 string
img
end
end
def file_decode(base, filename)
file = Tempfile.new([file_base_name(filename), file_extn_name(filename)])
file.binmode
file.write(Base64.decode64(base))
file.close
file
end
def file_base_name(file_name)
File.basename(file_name, file_extn_name(file_name))
end
def file_extn_name(file_name)
File.extname(file_name)
end
jQuery:
$(document).on("change", "#company_background_image", function(){
var output = this;
output.src = URL.createObjectURL(event.target.files[0]);
$(".img-container img").attr("src",output.src);
if ($(".img-preview.preview-lg img").size()!=0){
$(".img-preview.preview-lg img").attr("src",output.src);
}
$("#img-cropp").modal("show");
})
Controller:
def image_cropping
begin
Base64.decode64(img=params["crop-img"])
#getting only the string leaving out the data/<format>
img = file_decode(img.split(',')[1], @company.background_image.filename)
@company.background_image = img
@company.save
rescue Exception => e
#Returning if its not a base64 string
img
end
end
def file_decode(base, filename)
file = Tempfile.new([file_base_name(filename), file_extn_name(filename)])
file.binmode
file.write(Base64.decode64(base))
file.close
file
end
def file_base_name(file_name)
File.basename(file_name, file_extn_name(file_name))
end
def file_extn_name(file_name)
File.extname(file_name)
end
Thanks,
Hemant