Skip to content

Instantly share code, notes, and snippets.

@abitdodgy
Created January 10, 2014 16:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abitdodgy/8357018 to your computer and use it in GitHub Desktop.
Save abitdodgy/8357018 to your computer and use it in GitHub Desktop.
Generate a pre-signed url for S3 direct upload.
class SignedUrlsController < ApplicationController
def s3
# Create client and set bucket
client = AWS::S3.new
bucket = client.buckets[ENV['S3_BUCKET']]
# Extract file extension since we're renaming the file
extension = File.extname(params[:image_name]).downcase
# Get mime-type from extension
mime_type = Rack::Mime.mime_type(extension)
# Generate custom file name
file_name = SecureRandom.urlsafe_base64(5).downcase + extension
# Generate form data
# key cosists of custom directory 'u' for uploads;
# Current time to milisecond to integer and the file name we generated earlier
key = "u/#{(Time.now.to_f * 1000).to_i}/#{file_name}"
form = bucket.presigned_post(key: key, content_type: mime_type)
render json: form.fields
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment