Is there a way to download a file from s3 using th

2019-05-11 22:37发布

问题:

Ok so i tried two methods both failed

First method using the aws-s3 gem

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

UPDATE

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 

As you can see what i am trying to do is copy the mp3 from the s3 bucket and copy it to the local computer....any ideas on how to do this

回答1:

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

Basically you have to use the read and write methods on S3 objects.

So :

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


回答2:

If you are not forced to use the gem 'aws-s3', you might want to check out fog, which does basically the same things, only it is agnostic regarding the backend (aws, rackspace, ..), and seem to be more active. At the bottom of this page there's an example showing what you want to achieve