2015-10-12 68 views
4

我有一個擁有多個文件夾的AWS S3存儲桶。如何檢查AWS S3bucket中是否存在資源

s3 = AWS::S3.new 
bucket = s3.buckets['test'] 
bucket.exists? => true 

說我有一個名爲資源demo/index.html,我怎麼會檢查該資源是否存在於this bucket

可能是我的問題太簡單了,但我無法找到適當的答案。任何幫助表示讚賞。

回答

6

#存在嗎? ⇒布爾值

如果對象存在於S3中,則返回true。

# new object, does not exist yet 
obj = bucket.objects["my-text-object"] 
# no instruction file present 
begin 
    bucket.objects['my-text-object.instruction'].exists? #=> false 
rescue 
    # exists? can raise an error `Aws::S3::Errors::Forbidden` 
end 


# store the encryption materials in the instruction file 
# instead of obj#metadata 
obj.write("MY TEXT", 
    :encryption_key => MY_KEY, 
    :encryption_materials_location => :instruction_file) 

begin 
    bucket.objects['my-text-object.instruction'].exists? #=> true 
rescue 
    # exists? can raise an error `Aws::S3::Errors::Forbidden` 
end  

http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/S3Object.html#exists%3F-instance_method

+0

感謝@Arsen,我應了下來投給了這一點。我只是錯過了'?'在'存在嗎?'方法。高度讚賞你的迴應。 – ejo

+0

這裏有一些意想不到的行爲 - 如果對象存在,'exists?'將返回'true'。但否則會引發'Aws :: S3 :: Errors :: Forbidden'錯誤!你可以拯救這個錯誤,並將其解釋爲'false'。 SMH –

+0

@maxpleaner謝謝。我更新了答案。 – Arsen

相關問題