在这里,我尝试使用ajax将图像保存在mysql数据库中,但是每次上传图像失败时,请帮我解决这个问题。
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
我创建的图像我要将该图像转换为画布并单击保存按钮,通过执行两个功能来保存图像,使用该控制器可以获取图像但无法存储到数据库。
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");
}
});
});
每次我收到类似IOError的错误时(关闭流)
我需要通过单击保存按钮将图片保存到mysqldatabase中
有问题的线是
file.close
sub.testimonialpic = file
当mysql2
尝试将an保存IO
到BLOB列时,IO
必须将其打开才能读取。您只是在保存文件之前显式关闭了该文件(是IO)。
解决方法是
file.rewind
sub.testimonialpic = file
并在编辑ensure
之前在块中关闭该文件unlink
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句