问题
How can I check if some folder exists in my s3 bucket using Ruby on Rails?
I’m using AWS:S3 official gem After initializing the global connection
AWS::S3::Base.establish_connection!(:access_key_id => 'my_key_id', :secret_access_key => ‘my_secret’)
I have bucket named: myfirstbucket
With folder inside named: my_folder
With file inside my_folder named: my_pic.jpg
When I try to check if my_pic.jpg
exist it work just fine
s3object.exists? “/my_folder/my_pic.jpg” , “myfirstbucket”
=> True
How can I check only if the folder exists?
s3object = AWS::S3::S3Object
s3object.exists? “/my_folder/” , “myfirstbucket”
=> False
回答1:
Use Bucket#objects
:
bucket.objects({prefix: 'my/folder/'}).limit(1).any?
Returns a
Collection
ofObjectSummary
resources. No API requests are made until you call an enumerable method on the collection.Client#list_objects
will be called multiple times until everyObjectSummary
has been yielded.—http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Bucket.html#objects-instance_method
回答2:
You have to check
- object key with trailing slash "/" is exists
- If not exists, Is there any item in the directory?
For example:
You have file "my_file" under folder "my_folder".
The AWS S3 record my_folder/my_file
will exist offcourse, but my_folder/
may not exists.
So you have to check twice
if bucket.object("my_folder/").exists?
true
else
bucket.objects({prefix: "my_folder/"}).limit(1).any?
end
See the document: http://docs.aws.amazon.com/AmazonS3/latest/UG/FolderOperations.html
回答3:
You could make a tree from you bucket.
http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/Tree.html
tree = bucket.as_tree
tree.children.select(&:branch?).collect(&:prefix).include?(“/my_folder/”)
来源:https://stackoverflow.com/questions/38285326/check-if-folder-exist-in-s3-bucket