2015-04-06 115 views
5

我想上传一个文件。一个简单的hello.txt。我正在关注文档,并且无法将其上传到我的存储区。上传使用Ruby SDK文件到Amazon S3

# START AWS CLIENT 

s3 = Aws::S3::Resource.new 
bucket = s3.bucket(BUCKET_NAME) 

begin 

    s3.buckets[BUCKET_NAME].objects[KEY].write(:file => FILE_NAME) 
    puts "Uploading file #{FILE_NAME} to bucket #{BUCKET_NAME}." 

    bucket.objects.each do |obj| 
    puts "#{obj.key} => #{obj.etag}" 
    end 

rescue Aws::S3::Errors::ServiceError 
    # rescues all errors returned by Amazon Simple Storage Service 
end 

我下面http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpRuby.html

错误:

➜ s3-tester ruby main.rb /Users/.rvm/gems/ruby-2.1.1/gems/aws-sdk-resources-2.0.34/lib/aws-sdk-resources/collection.rb:79:in 'method_missing: undefined method []' for ' <Aws::Resources::Collection:0x000001031e5100> (NoMethodError)' from 'main.rb:18:in <main> '

+0

有什么问题MY_BUCKET? –

+0

我得到[]没有方法错误 –

+0

好的...把错误的问题。 –

回答

2
client = Aws::S3::Client.new(region: 'us-east-1') 
resource = Aws::S3::Resource.new(client: client) 
bucket = resource.bucket(BUCKET_NAME) 
begin 
    # s3.buckets[BUCKET_NAME].objects[KEY].write(:file => FILE_NAME) 
    # puts "Uploading file #{FILE_NAME} to bucket #{BUCKET_NAME}." 

    bucket.objects.each do |o| 
    puts o.key 
    end 

rescue Aws::S3::Errors::ServiceError 
    # rescues all errors returned by Amazon Simple Storage Service 
end 
+0

我没有问题连接到S3。我设定了我的地区,并声称。我不能上传文件。一个简单的文件.. –

+0

你想要什么定义s3,因为是客户端,而不是资源 –

+0

我试过这两种方式。 –

7

的主要问题是,你有AWS的SDK安装了Ruby的第2版,但你引用版本1的文档。第2版​​的文档可以在这里找到:

http://docs.aws.amazon.com/sdkforruby/api/index.html

要更新您的示例使用的版本2:

s3 = Aws::S3::Resource.new 
bucket = s3.bucket(BUCKET_NAME) 

begin 

    bucket.object(KEY).upload_file(FILENAME) 
    puts "Uploading file #{FILE_NAME} to bucket #{BUCKET_NAME}." 

    bucket.objects.each do |obj| 
    puts "#{obj.key} => #{obj.etag}" 
    end 

rescue Aws::S3::Errors::ServiceError 
    # rescues all errors returned by Amazon Simple Storage Service 
end 

的主要区别:

  • 1版使用#[]方法在集合上引用一个对象的密钥。版本2有两种方法,#objects()#object(key)。后者是吸气剂。前者枚举桶中的所有对象。
  • 版本2有一个专门的#upload_file方法,管理从磁盘上传对象。这与版本1中的#write类似,但它也可以使用多个线程并行上传大型对象部分。
1

我使用了类似以下的脚本,如果它不存在,就会创建一个新的存储桶,然后将选定的文件上传到它。

#!/usr/bin/env ruby 
# 

require 'rubygems' 
require 'aws-sdk' 

bucket_name = ARGV[0] 
file_name = ARGV[1] 


# Get an instance of the S3 interface. 
s3 = Aws::S3::Client.new(region: 'us-east-1') 

key = File.basename(file_name) 
resp = s3.list_buckets() 
buckets = resp.data.buckets 

if buckets.select { |b| b.name == bucket_name }.length == 0 
    puts 'creating bucket' 
    s3.create_bucket(bucket: bucket_name) 
end 

puts "Uploading file #{file_name} to bucket #{bucket_name}..." 

# Upload a file. 
s3.put_object(
    :bucket => bucket_name, 
    :key => key, 
    :body => IO.read(file_name) 
) 

,如果你保存,为您upload.rb可以上传simple.txt运行

$ ruby upload.rb my_bucket simple.txt

相关问题