Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an S3 object in a bucket with one Fog call?

Tags:

ruby

fog

Here is the Fog walkthrough of creating a file (an S3 object) in a directory (an S3 bucket):

connection = Fog::Storage.new({
  :provider                 => 'AWS',
  :aws_access_key_id        => YOUR_AWS_ACCESS_KEY_ID,
  :aws_secret_access_key    => YOUR_AWS_SECRET_ACCESS_KEY
})

directory = connection.directories.create(
  :key    => "fog-demo-#{Time.now.to_i}", # globally unique name
  :public => true
)

file = directory.files.create(
  :key    => 'resume.html',
  :body   => File.open("/path/to/my/resume.html"),
  :public => true
)

But it looks to me as though this requires 2 API calls:

  1. connection.directories.create
  2. directory.files.create

If I already have the directory (an S3 bucket) created, how do I create an file (an S3 object) with only one Fog call?

like image 241
David J. Avatar asked Sep 05 '12 19:09

David J.


People also ask

How many buckets by default can you create in a single AWS account?

By default, you can create up to 100 buckets in each of your AWS accounts. If you need additional buckets, you can increase your account bucket limit to a maximum of 1,000 buckets by submitting a service limit increase.

What is an s3key?

The object key (or key name) uniquely identifies the object in an Amazon S3 bucket. When you create an object, you specify the key name, which uniquely identifies the object in the bucket. For example, on the Amazon S3 console , when you highlight a bucket, a list of objects in your bucket appears.


2 Answers

If you know the directory exists you can do

dir = connection.directories.new(:key => 'foo')# no request made
dir.files.create(...)
like image 119
Frederick Cheung Avatar answered Sep 30 '22 15:09

Frederick Cheung


Or, if already have a bucket in which you want to store the file, then what you can do it is the following:

bucket = connection.directories.get({BUCKET_NAME})

and after that, you will be able to call bucket.files.create, to store files on that bucket.

Hope it helps!

like image 45
facundofarias Avatar answered Sep 30 '22 15:09

facundofarias