Skip to content

Instantly share code, notes, and snippets.

@unavailabl3
Last active February 8, 2019 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unavailabl3/0a51871b40ce30923b9d299c34f73189 to your computer and use it in GitHub Desktop.
Save unavailabl3/0a51871b40ce30923b9d299c34f73189 to your computer and use it in GitHub Desktop.
AWS S3 upload file with Ruby/Rails
Using gem aws-sdk for a ror application for uploading images to s3
Uploading images to a fixed bucket with different folders for each object or application.
The s3 keeps a limitation on the number of buckets creattion whereas there is no
limitation for content inside a bucket.
This code will upload image for a user to s3 using aws-sdk gem. The bucket and the image uploaded are made public
so that the images uploaded are directly accessible
Method for aws-sdk v3
1. In bash (terminal) set ENV vars
export AWS_ACCESS_KEY_ID='your_key_id'
export AWS_SECRET_ACCESS_KEY='your_secret_key'
2. code to upload
require 'aws-sdk'
s3 = Aws::S3::Resource.new(region: 'us-east-2') #check your region in s3 dashboard
bucket = 'your_bucket_name'
name = File.basename('/path/to/file.jpg')
obj = s3.bucket(bucket).object(name)
obj.upload_file(image_location)
obj.public_url.to_s #returns public url of file at s3 server
If smth wrong check:
-region
-bucket_name and if it exists
-permissions in s3 dashboard
-CORS configuration, for example
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://localhost:3000</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment