Skip to content

Instantly share code, notes, and snippets.

@eladkehat
Created December 24, 2011 07:56
Show Gist options
  • Save eladkehat/1516746 to your computer and use it in GitHub Desktop.
Save eladkehat/1516746 to your computer and use it in GitHub Desktop.
Use S3 (via the aws gem) in Rails to store user files such as images
# Place this file in config/initializers
# load the libraries
require 'aws'
# log requests using the default rails logger
AWS.config(:logger => Rails.logger)
# here's how to load credentials from a file
#config_path = File.expand_path(File.dirname(__FILE__)+"/../aws.yml")
#AWS.config(YAML.load(File.read(config_path)))
# we load credentials from the environment
AWS.config(:access_key_id => ENV['S3_KEY'])
AWS.config(:secret_access_key => ENV['S3_SECRET'])
# Controller for storing and retrieving user assets, such as local files
class UserAssetsController < ApplicationController
S3_BUCKET = 'your-user-assets-bucket-name'
def put
if params[:asset]
s3 = AWS::S3.new
bucket = s3.buckets[S3_BUCKET]
obj = bucket.objects[s3_filename(params[:user_id], filename)]
obj.write params[:image].tempfile
render :text => obj.public_url
else
render :text => '{error}'
end
end
def get
s3 = AWS::S3.new
bucket = s3.buckets[S3_BUCKET]
obj = bucket.objects[s3_filename(params[:user_id], params[:filename])]
#TODO - get the file type, send with :type => image.content_type
send_data obj.read, :disposition => 'inline', :filename => params[:filename]
end
protected
def s3_filename(user_id, filename)
prefix = Rails.env.production? ? '' : "#{Rails.env}/"
"#{prefix}#{CGI.escape(user_id)}/#{normalize_filename(filename)}"
end
# Make the original filename fit for storage on S3
def normalize_filename(filename)
filename
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment