Rocker Rocker - 26 days ago 12
jQuery Question

IOError (closed stream) in ruby while saving the image


here im trying to save the image in mysql database using ajax but each
time getting fail to upload the image, please help me out solve this.


Controller.rb

def image_converter
sub = TestimonialPicture.new
decoded_file = Base64.decode64(params[:picdata]) unless params[:picdata].nil?
if request.post?
begin
tmpfilename = "#{params[:id]}#{Time.now.to_i.to_s}"
file = Tempfile.new([tmpfilename, '.jpg'])
file.binmode
file.write decoded_file
file.close
sub.testimonialpic = file
if sub.save
sub.update_attributes(:testimonial_id => params[:tid])
msg = "YOur image has been successfully uploaded"
else
msg = "Failed to create submission. Please try again"
end
ensure
file.unlink
end
render :text=>msg
end
end



the image which i have created im going to convert that one to canvas
and saving, by clicking save button two functions im doing, using that
controller im able to get the image but but unable to store to
database.

view.html.erb


$(document).ready(function(){
var element = $("#bgcolor"); // global variable
var getCanvas; // global variable

$("#save_btn").on('click', function () {
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});

$("#btn-Convert-Html2Image").on('click', function () {
$("#popDiv").hide();
var picdata = getCanvas.toDataURL("image/png");
var pic = picdata.replace(/^data:image\/(png|jpg);base64,/, "");
var tid = $("#tid").val();
$.ajax({
url: "/businessdb/image_converter",
type: "POST",
data: {"pic" : pic, "tid" : tid},
dataType: "json",
success: function(data) {
location.reload();
alert("success");
}
});
});



each time im getting an error like IOError(closed stream)

I need to save my picture into mysqldatabase by clicking save button

Answer

The problematic lines are

file.close
sub.testimonialpic = file

When the mysql2 tries to save an IO to a BLOB column, that IO must be open to read. You just explicitly closed that file (which is an IO) before it is saved.

The solution is

file.rewind
sub.testimonialpic = file

And close that file in the ensure block before it's unlinked.