9

当我为单个文件执行此操作时:

    aws_s3 = AWS::S3.new(S3_CONFIG)
    bucket = aws_s3.buckets[S3_CONFIG["bucket"]]

    object = bucket.objects["user/1/photos/image_1.jpg"]
    new_object = bucket.objects["users/1/photos/image_1.jpg"]
    object.copy_to new_object, {:acl => :public_read}

但我想移动整个“/photos”文件夹 throws No Such Key。s3 键可能只是每个文件的完整路径。怎么做?

    aws_s3 = AWS::S3.new(S3_CONFIG)
    bucket = aws_s3.buckets[S3_CONFIG["bucket"]]

    object = bucket.objects["user/1/photos"]
    new_object = bucket.objects["users/1/photos"]
    object.copy_to new_object, {:acl => :public_read}

谢谢!

4

3 回答 3

5

做到了:

bucket.objects.with_prefix("user/1/photos").each do |object|
   ...
end
于 2012-12-14T20:03:02.520 回答
1

我需要额外的代码才能让它工作。基本上从源前缀中切掉基础,然后将其添加到目标前缀:

def copy_files_s3(bucket_name, source, destination)
  source_bucket = @s3.buckets[bucket_name]
  source_bucket.objects.with_prefix(source).each do |source_object|
    new_file_name = source_object.key.dup
    new_file_name.slice! source
    new_object = source_bucket.objects["#{destination}#{new_file_name}"]
    source_object.copy_to new_object, {acl: :public_read}
  end
end
于 2015-10-27T08:14:49.253 回答
1

“文件夹”在 S3 中不是对象,这就是为什么您无法通过键获取它的原因,但文件夹路径实际上是文件夹包含的对象的所有键的前缀。

另一件重要的事情是,您必须对密钥进行 url 编码,否则您可能会遇到未知密钥错误。

require 'aws-sdk'
require 'aws-sdk-s3'
require 'securerandom'
require 'uri'
require "erb"
include ERB::Util

def copy_folder(folder, destination)
    bucket_name = 'your_bucket'
    credentials = Aws::Credentials.new('key', 'secret')
    s3_client = Aws::S3::Client.new(region:'the_region', credentials: credentials)
    enumerate_keys_with_prefix(source).each do |source_object|
       source_key = url_encode(source_object.key)
       destination_key = source_object.key.dup.sub(source, "")
       s3_client.copy_object({bucket: bucket_name, copy_source: bucket_name+'/'+source_key, key: destination+'/'+destination_key, acl: "public-read"})
    end
end

def enumerate_keys_with_prefix(prefix)
    bucket_name = 'your_bucket'
    credentials = Aws::Credentials.new('key', 'secret')
    s3 = Aws::S3::Resource.new(region:'the_region', credentials:credentials)
    return s3.bucket(bucket_name).objects(prefix: prefix)
end
于 2018-03-05T14:52:31.733 回答