I am trying to save file from a URL and then save it to S3. This is the rake task code that I've written:
require 's3'
require 'open-uri'
task :testing => [:environment] do
aws_object = S3::Service.new(access_key_id: Rails.application.secrets.aws_access_key_id, secret_access_key: Rails.application.secrets.aws_secret_access_key)
bucket = aws_object.buckets.find(Rails.application.secrets.aws_bucket)
url = 'https://pbs.twimg.com/profile_images/1111729635610382336/_65QFl7B_400x400.png'
downloded_file = open(url)
new_file = bucket.objects.build('twitter.jpg')
new_file.content = (File.read downloded_file)
if new_file.save
puts "Success!"
end
end
But when I run this rake task code above, this is what I got on my terminal:
rake aborted!
S3::Error::ResponseError: S3::Error::ResponseError
/Users/ryzal/Sites/test/lib/tasks/testing.rake:17:in `block in <top (required)>'
/Users/ryzal/.rbenv/versions/2.3.1/bin/bundle:23:in `load'
/Users/ryzal/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'
Tasks: TOP => testing
(See full trace by running task with --trace)
I've checked all my S3 details and all are correct. Can somebody help? Thanks!
I've finally solved this and this is how I did it:
1) I use aws-sdk-ruby gem instead of s3
gem
2) I refer S3 documentation here and renew my code to this:
require 'aws-sdk-s3'
require 'open-uri'
task :testing => [:environment] do
s3 = Aws::S3::Resource.new(region: Rails.application.secrets.aws_region)
obj = s3.bucket(Rails.application.secrets.aws_bucket).object("any_unique_key_you_want_such_as_email_or_username")
url = 'https://pbs.twimg.com/profile_images/1111729635610382336/_65QFl7B_400x400.png'
file = open(url)
obj.put(body: file, acl: "public-read")
puts "URL is: #{obj.public_url}"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.