11

So, I managed to get an image blob into my MySQL database (there's a big hex number in the field), but I can't find any documentation on how to display the image in a rails environment... when it prints out, it starts with a GIF89... and then the gobbledygook characters you see in a GIF when you open it in Notepad. : P Any clues would be greatly appreciated!

Thanks.

3 Answers 3

27

The following code should work. In your controller, create a method:


def show_image
    @user = User.find(params[:id])
    send_data @user.image, :type => 'image/png',:disposition => 'inline'
end

In your view:


<%= image_tag url_for(:controller => "mycontroller", :action => "show_image", :id => @user.id) %>

I would recommend using the Paperclip gem. It makes saving/viewing of images really easy.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that works. Paperclip will probably be the way I ultimately go, but I needed a quick and dirty solution for demo purposes.
@wulftone. Glad to be of assistance.
16

Because you mentioned "quick and dirty", I'll throw out this as an alternative-

<%= ('<img src="data:image/jpg;base64,%s">' % Base64.encode64(@the_data)).html_safe %>

I think this is closest to what you wanted to do. There's a few reasons that this code shouldn't be used as-is, but it's simple. I'd have to think more about how bad of an idea is it is to mark the whole thing as html_safe. Also, this wouldn't work in older versions of IE.

2 Comments

I've just extracted it into a helper :)
I also wonder what %s">' % Base64.encode64(@.... part means??? (percent followed by s followed again by percent)
5

You should also add

resources :users do
     get 'show_image', :on => :collection
 end

or

get users/show_image" => "users#show_image"

before

resources :users in route.rb file

1 Comment

@silvio Rails 4 will complaint: ActionView::Template::Error (No route matches {:controller=>"user_controller", :action=>"show_image", :id=>9777}):

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.