Created
December 24, 2011 07:56
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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']) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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