How to list all files in an s3 folder using AWS-SDK gem in ruby on rails

Solution 1:

Too late answer but better than never.

You can do

s3_bucket.objects.with_prefix('folder_name').collect(&:key)

According to official documentation here

Updates: SDK V3

s3 = Aws::S3::Client.new
resp = client.list_objects_v2({
  bucket: "BucketName", # required
  prefix: "FolderName", 
})

Solution 2:

You can use this small piece of code for getting list of files for a specific folder.

 s3 = Aws::S3::Resource.new(region: 'ap-southeast-1', access_key_id: ENV['AWS_ACCESS_KEY_ID'], secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'] )
 data_files = s3.bucket(bucket_name).objects(prefix: 'prefix/', delimiter: 'delimiter').collect(&:key)

Solution 3:

https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/S3/Client.html#list_objects_v2-instance_method

SDK V3 has the prefix option for client!

resp = client.list_objects_v2({ bucket: "BucketName", # required prefix: "FolderName", })