How to list all files in an S3 folder using Fog in Ruby

Gerry Shaw picture Gerry Shaw · Apr 11, 2013 · Viewed 10.4k times · Source

How do I list all the files in a specific S3 "directory" using Fog?

I know that S3 doesn't store files in folders but I need a way to limit the returned files to specific "folder" instead of retrieving the entire list in the bucket.

Answer

Gerry Shaw picture Gerry Shaw · Apr 11, 2013

Use the prefix option on the directory.get method. Example:

def get_files(path, options)
  connection = Fog::Storage.new(
    provider: 'AWS',
    aws_access_key_id: options[:key],
    aws_secret_access_key: options[:secret]
  )
  connection.directories.get(options[:bucket], prefix: path).files.map do |file|
    file.key
  end
end