Rails:无法从URL保存文件并将其保存到Amazon S3(S3 :: Error :: ResponseError)

问题描述 投票:0回答:1

我试图从URL保存文件,然后将其保存到S3。这是我写的rake任务代码:

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

但是当我在上面运行这个rake任务代码时,这就是我在终端上得到的:

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)

我检查了所有S3细节,一切都正确。有人可以帮忙吗?谢谢!

ruby-on-rails amazon-web-services amazon-s3 ruby-on-rails-5
1个回答
0
投票

我终于解决了这个问题,这就是我做到的:

1)我使用aws-sdk-ruby gem而不是s3 gem

2)我引用S3文档here并将我的代码更新为:

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
© www.soinside.com 2019 - 2024. All rights reserved.