Rename Object in S3 using Ruby

2019-06-25 10:35发布

问题:

I want to rename an item in s3 using the Ruby sdk. How do I do this?

I have tried:

require 'aws-sdk'
s3 = AWS.config(
        :region => 'region',
        :access_key_id => 'key',
        :secret_access_key => 'key'
)

b = AWS::S3::Bucket.new(client: s3, name: 'taxalli')


    b.objects.each do |obj|
       obj.rename_to('imports/files/' + line.split(' ').last.split('/').last)
      end

But I dont see anything in the new sdk for moves or renames.

回答1:

There is no such thing as renaming in the Amazon S3 SDK. Basically what you have to do is copy the object and then delete the old one.

    require 'aws-sdk'
    require 'open-uri'


    creds = Aws::SharedCredentials.new(profile_name: 'my_profile')

    s3 = Aws::S3::Client.new( region: 'us-east-1',
                              credentials: creds)



    s3.copy_object(bucket: "my_bucket",
                   copy_source: URI::encode("my_bucket/MyBookName.pdf"),
                   key: "my_new_book_name.pdf")

    s3.delete_object(bucket: "my_bucket",
                     key: "MyBookName.pdf")


回答2:

In AWS-SDK version 2 is now method called "move_to" (http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Object.html#move_to-instance_method) which you can use in this case. Technically it will still copy & delete that file on S3 but you don't need to copy & delete it manually and most importantly it will not delete that file if that copy action fails from some reason.



回答3:

have you Rails Paperclip S3 rename thousands of files? or https://gist.github.com/ericskiff/769191 ?