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

2

11

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?

Became answered 5/9, 2012 at 19:5 Comment(0)
P
17

If you know the directory exists you can do

dir = connection.directories.new(:key => 'foo')# no request made
dir.files.create(...)
Pope answered 5/9, 2012 at 19:39 Comment(0)
S
3

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!

Statehood answered 21/10, 2014 at 7:23 Comment(3)
This needs different access permissions though: ListAllMyBuckets and GetBucketLocation on all buckets.Imagism
@JosuaSchmid Good catch! :)Statehood
This makes an unnecessary extra request.Aetolia

© 2022 - 2024 — McMap. All rights reserved.