alucillo36
alucillo36

Reputation: 91

Displaying the image saved to the database as blob correctly

I have a web application on Rails and now I am about to seed some data. I am stuck on displaying the image that is saved as a blob type in database.

In my seeds.rb

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

The image (stewart.jpg):

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

In my left.html.erb file where the image is displayed:

<%= ("<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 %>

After the seeding, I checked the database using SQLite browser and I confirmed that the image has been read. But when I rendered left.html.erb, here is what the image looked like:

The image rendered:
http://postimg.org/image/mnr9bo5yl/5aea8b27/

Additionally, the data type in migration file is binary in which the equivalent type in sqlite is blob, and I don't want to use extra gems like paperclip and the like.

Thanks in advance.

Upvotes: 3

Views: 2383

Answers (1)

alucillo36
alucillo36

Reputation: 91

This solved the problem:

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

The line above reads the file in binary mode.

Thanks to Mr. Bryan Bibat of Ruby Users Group - Philippines (https://www.facebook.com/groups/phrug/)

Upvotes: 3

Related Questions