Skip to content

Instantly share code, notes, and snippets.

@hollanddd
Created January 23, 2013 15:52
Show Gist options
  • Save hollanddd/4608505 to your computer and use it in GitHub Desktop.
Save hollanddd/4608505 to your computer and use it in GitHub Desktop.
=begin
There are better alternatives to storing images as a blob in the db like amazon s3,
but I don't have a choice in this case
rails g model image file_name:string content_type:string file_size:integer file_data:binary
populate in the console
rails c
require 'net/http'
=> true
host = 'host_url'
path = 'path_to_photo'
res = Net::HTTP.get_response(host, path)
=> #<Net::HTTPOK 200 OK readbody=true>
Image.create!(file_name: 'something',
content_type: res['Content-type'],
file_size: res.body.size,
file_data: res.body
)
=> #<Image id: 1, file_name: "something"...
config/routes.rb
match '/images/*file_name', controller: 'images', action: :show
=end
class ImagesController < ApplicationController
caches_page :show
def show
if @image = Image.find_by_file_name(params[:file_name])
send_data(@image.file_data,
type: @image.content_type,
filename: @image.file_name,
disposition: 'inline'
)
else
render text: 'no soup for you'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment