Check if folder exist in s3 bucket

谁都会走 提交于 2021-02-16 13:16:12

问题


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 of ObjectSummary resources. No API requests are made until you call an enumerable method on the collection. Client#list_objects will be called multiple times until every ObjectSummary has been yielded.

—http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Bucket.html#objects-instance_method




回答2:


You have to check

  1. object key with trailing slash "/" is exists
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!