简体   繁体   English

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

[英]Rails: Can't save file from URL and save it to Amazon S3 (S3::Error::ResponseError)

I am trying to save file from a URL and then save it to S3. 我试图从URL保存文件,然后将其保存到S3。 This is the rake task code that I've written: 这是我写的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

But when I run this rake task code above, this is what I got on my terminal: 但是当我在上面运行这个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)

I've checked all my S3 details and all are correct. 我检查了所有S3细节,一切都正确。 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 1)我使用aws-sdk-ruby gem而不是s3 gem

2) I refer S3 documentation here and renew my code to this: 2)我在这里引用S3文档并将我的代码更新为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM