正确显示保存到数据库的图像为blob

时间:2013-11-21 09:49:52

标签: ruby-on-rails ruby-on-rails-3 image sqlite

我在Rails上有一个Web应用程序,现在我要播种一些数据。我坚持在数据库中显示保存为blob类型的图像。

在我的 seeds.rb

user = User.find(1)
file = File.open("db/seeds/images/stewart.jpg").read
user.user_image = file
user.save!

图片( stewart.jpg ):

  

http://postimg.org/image/qyjagb2xf/1418c08f/

在我的 left.html.erb文件中显示图片:

<%= ("<img id = 'profile-image' width = '80' height = '80' alt = 'image' class = 'list_image' src='data:image/jpg;base64,%s'>" % Base64.encode64(@user.user_image)).html_safe %>

播种后,我使用SQLite浏览器检查了数据库,并确认图像已经存在 读。但是当我渲染left.html.erb时,图像看起来像是这样的:

呈现的图像:
http://postimg.org/image/mnr9bo5yl/5aea8b27/

此外,迁移文件中的数据类型是二进制文件,其中sqlite中的等效类型是blob,我不想使用像paperclip之类的额外宝石。

提前致谢。

1 个答案:

答案 0 :(得分:3)

这解决了这个问题:

  

file = File.open(“db / seeds / images / stewart.jpg”,“rb”)。read

上面的行以二进制模式读取文件。

感谢Ruby Users Group的Bryan Bibat先生 - 菲律宾(https://www.facebook.com/groups/phrug/

相关问题