有没有办法使用ruby gem aws-s3从s3下载文件?

时间:2012-03-16 16:23:43

标签: ruby-on-rails ruby rubygems amazon-s3

好的,所以我尝试了两种方法都失败了

使用aws-s3宝石的第一种方法

require 'aws/s3'
S3ID = "MYACCESS"
S3KEY = "MYKEY"
include AWS::S3
AWS::S3::Base.establish_connection!(
  :access_key_id     => S3ID,
  :secret_access_key => S3KEY
)

bucket = AWS::S3::Bucket.find("test_bucket")
 => #<AWS::S3::Bucket:0x007fea3e2898c8 @attributes={"xmlns"=>"http://s3.amazonaws.com/doc/2006-03-01/", "name"=>"test_bucket", "prefix"=>nil, "marker"=>nil, "max_keys"=>1000, "is_truncated"=>true}, @object_cache=[#<AWS::S3::S3Object:0x70322020960960 '/test_bucket/00000188110119_1000000731213/'>, #<AWS::S3::S3Object:0x70322020960660 '/test_bucket/00000188110119_1000000731213/10_08-52-08.mp3'>, #<AWS::S3::S3Object:0x703220209

bucket.size
 => 1000 

bucket.objects[0]
 => #<AWS::S3::S3Object:0x70322028046080 '/test_bucket/00000188110119_1000000731213/'> 
bucket.objects[1]
 => #<AWS::S3::S3Object:0x70322028046040 '/test_bucket/00000188110119_1000000731213/10_08-52-08.mp3'> 
bucket.objects[1].key
 => "00000188110119_1000000731213/10_08-52-08.mp3" 

File.open("/Users/matt/local_copy.mp3", "w") do |f|
  f.write(bucket.objects[1])
end

更新

bucket.objects[1]
 => #<AWS::S3::S3Object:0x70322028046040 '/test_bucket/00000188110119_1000000731213/10_08-52-08.mp3'> 
bucket.objects[1].read
 NoMethodError: undefined method `read' for #<AWS::S3::S3Object:0x70322028046040>
bucket.objects[1].class
 => AWS::S3::S3Object 

你可以看到我想要做的是从s3存储桶中复制mp3并将其复制到本地计算机....任何有关如何执行此操作的想法

2 个答案:

答案 0 :(得分:7)

见: http://docs.amazonwebservices.com/AWSRubySDK/latest/AWS/S3/S3Object.html

基本上,您必须在S3对象上使用readwrite方法。

所以:

File.open("/Users/matt/local_copy.mp3", "w") do |f|
  f.write(bucket.objects[1].read)
end

答案 1 :(得分:0)

如果您没有被迫使用gem'aws-s3',您可能需要查看fog,它基本上做同样的事情,只是它对后端是不可知的(aws,rackspace ,. 。),似乎更活跃。在this page的底部有一个显示您想要实现的内容的示例