Tom Rossi
Tom Rossi

Reputation: 12066

Uploading and Downloading Files using fog

When uploading and downloading files using fog, I've seen a couple different ways to do it. Which is preferred or does it even matter?

Uploading

directory.files.create(key: local_filename,
                       body: File.open(local_path),
                       public: false)

or

connection.put_object(directory.key, 
                      local_filename,
                      File.open(local_path),
                      public: false)

and for downloading I only have one example, but needed to change the file options to 'wb' to get it to work:

Downloading

File.open(Rails.root.join(file.key), 'wb') do |local_file|
  local_file.write(file.body)
end

Upvotes: 0

Views: 1423

Answers (1)

geemus
geemus

Reputation: 2542

Great questions.

The directory.files.create version ends up calling connection.put_object under the covers, so functionally they should be equivalent in basic usage. That being said, directory.files.create is the preferred option because it allows you (in many cases) to change which storage provider you are using and have things "just work" (even if the method for uploading on that provider looks quite different).

On the downloading side, there should be a similiar directory.files.get vs connection.get_object type distinction to get a reference to the object. You'll want the directory version, and then calling the body method, as you do, should give you the contents to do with as you need to.

Hope that clarifies.

Upvotes: 1

Related Questions