如何使用aws-s3 gem在存储桶之间复制文件

aws-s3文档说:

# Copying an object S3Object.copy 'headshot.jpg', 'headshot2.jpg', 'photos' 

但是,如何将heashot.jpgphotos桶复制到archive桶中

谢谢!

德布

AWS-SDK gem。 S3Object#copy_to

 Copies data from the current object to another object in S3. S3 handles the copy so the client does not need to fetch the data and upload it again. You can also change the storage class and metadata of the object when copying. 

它使用copy_object方法内部 ,因此复制function允许您复制S3存储桶内或之间的对象,并可选择替换与进程中的对象关联的元数据。

标准方法(下载/上传)

在此处输入图像描述

复制方法

在此处输入图像描述

代码示例:

 require 'aws-sdk' AWS.config( :access_key_id => '***', :secret_access_key => '***', :max_retries => 10 ) file = 'test_file.rb' bucket_0 = {:name => 'bucket_from', :endpoint => 's3-eu-west-1.amazonaws.com'} bucket_1 = {:name => 'bucket_to', :endpoint => 's3.amazonaws.com'} s3_interface_from = AWS::S3.new(:s3_endpoint => bucket_0[:endpoint]) bucket_from = s3_interface_from.buckets[bucket_0[:name]] bucket_from.objects[file].write(open(file)) s3_interface_to = AWS::S3.new(:s3_endpoint => bucket_1[:endpoint]) bucket_to = s3_interface_to.buckets[bucket_1[:name]] bucket_to.objects[file].copy_from(file, {:bucket => bucket_from}) 

使用right_aws gem:

 # With s3 being an S3 object acquired via S3Interface.new # Copies key1 from bucket b1 to key1_copy in bucket b2: s3.copy('b1', 'key1', 'b2', 'key1_copy') 

我碰到的问题是,如果你有pics/1234/yourfile.jpg那么bucket只是picskey1234/yourfile.jpg

我从这里得到了答案: 如何使用rails应用程序中的s3在存储桶之间复制文件?

使用AWS SDK gem的copy_from或copy_to时,默认情况下会复制三件事:ACL,存储类或服务器端加密。 您需要将它们指定为选项。

 from_object.copy_to from_object.key, {:bucket => 'new-bucket-name', :acl => :public_read} 

https://github.com/aws/aws-sdk-ruby/blob/master/lib/aws/s3/s3_object.rb#L904

这是一个简单的ruby类,用于将所有对象从一个存储桶复制到另一个存储桶: https : //gist.github.com/edwardsharp/d501af263728eceb361ebba80d7fe324

我相信,为了在存储桶之间进行复制,您必须从源存储桶中读取文件的内容,然后通过应用程序的存储空间将其写回目标存储桶。 有一个片段在这里使用aws-s3显示这个,另一种方法在这里使用right_aws

aws-s3 gem无法在不将文件移动到本地计算机的情况下在存储桶之间复制文件。 如果您认为这是可行的,那么以下内容将起作用:

 AWS::S3::S3Object.store 'dest-key', open('http://url/to/source.file'), 'dest-bucket' 

我遇到了你遇到的同样的问题,所以我克隆了AWS-S3的源代码并创建了一个分支,它有一个copy_to方法,允许在桶之间进行复制,我已经捆绑到我的项目中并在需要时使用那个function。 希望其他人也会觉得这很有用。

在GitHub上查看分支 。

对于任何仍在寻找的人,AWS都有相关文档 。 使用aws-sdk gem实际上非常简单:

 bucket = Aws::S3::Bucket.new('source-bucket') object = bucket.object('source-key') object.copy_to(bucket: 'target-bucket', key: 'target-key')