我尝试创建一个删除S3实例上文件的方法,但是当我尝试调用AWS::S3::Errors::NoSuchKey: No Such Key
或。.head
时,我收到read
错误一个对象。
def thumbnail
{
exists: thumbnailable?,
small: "http://#{bucket}.s3.amazonaws.com/images/#{id}/small_thumb.png",
large: "http://#{bucket}.s3.amazonaws.com/images/#{id}/large_thumb.png"
}
end
module Adapters
module AmazonS3
class Accessor
S3_BUCKET = AWS::S3.new.buckets[ENV['AMAZON_BUCKET']]
...
def self.delete_file(thumbnail)
prefix_pattern = %r{http://[MY-S3-HOST]-[a-z]+.s3.amazonaws.com/}
small_path = thumbnail[:small].sub(prefix_pattern, '')
large_path = thumbnail[:large].sub(prefix_pattern, '')
small = S3_BUCKET.objects[small_path]
large = S3_BUCKET.objects[large_path]
binding.pry
S3_BUCKET.objects.delete([small, large])
end
end
end
end
"http://projectname-staging.s3.amazonaws.com/images/994/small_thumb.png"
"http://projectname-production.s3.amazonaws.com/images/994/large_thumb.png"
答案 0 :(得分:1)
为ruby假设awssdk v1。
small = S3_BUCKET.objects[small_path]
实际上并没有获得任何对象。
来自:https://docs.aws.amazon.com/AWSRubySDK/latest/AWS/S3/Bucket.html
bucket.objects['key'] #=> makes no request, returns an S3Object
bucket.objects.each do |obj|
puts obj.key
end
因此您需要将代码更改为:
to_delete = []
S3_BUCKET.objects[small_path].each do |obj|
to_delete << obj.key
end
S3_BUCKET.objects[large_path].each do |obj|
to_delete << obj.key
end
S3_BUCKET.objects.delete(to_delete)
刚刚搞砸了代码,所以想法就在那里,你可能需要纠正/抛光一下
答案 1 :(得分:1)
由于您对@Mircea的回答,我能够得到一种不同的解决方案。
def self.delete_file(thumbnail)
folder = thumbnail[:small].match(/(\d+)(?!.*\d)/)
to_delete = []
S3_BUCKET.objects.with_prefix("images/#{folder}").each do |thumb|
to_delete << thumb.key
end
# binding.pry
S3_BUCKET.objects.delete(to_delete)
end