我有一个来自图片代码的源网址,我想将该图片上传到我的S3存储桶。我该怎么做?
答案 0 :(得分:4)
A-哈!我已经有了答案,但发现这很难找出......
不幸的是,如果没有先从源URL下载有问题的文件,我就无法完成此任务。
以下是我上传产品图片的方式:
首先在app / config / initializers / aws.rb
中配置S3存储桶Aws.config.update({
region: ENV['AWS_REGION'],
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
})
S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET_NAME'])
然后我创建了app / workers / aws_importer.rb
require 'aws-sdk'
class AwsImporter
def upload_from_url (img_url, product_name)
image_file = open(img_url) // stage file for saving locally
local_image_path = product_name + ".jpg" // define filename and designate to root directory
IO.copy_stream(image_file, local_image_path) // download file to root directory
remote_image_path = "/products/#{product_name}/primary_image/#{local_image_path}" // set the desired url path in AWS
S3_BUCKET.object(remote_image_path).upload_file(local_image_path) // upload file to S3
File.delete(local_image_path) // then delete the local file copy
"https://s3.amazonaws.com/#{S3_BUCKET.name}/" + remote_image_path // return the new url path of the uploaded object.
end
end
然后您需要做的就是致电:
AwsImporter.new.upload_from_url(img_url, product_name)
这正是我通过我们可以控制的Products和image_urls来抓取整个网站来为我们的数据库播种的方式。
答案 1 :(得分:0)
我知道这个问题很旧,但是我需要弄清楚这个问题,而无法获得完整的答案。
这是我的操作方式。
首先确保它变成一个TempFile。如果这不仅是一次性的事情,而且例如您正在Rails中做这件事……那么您可能想将其添加为初始化程序之类的东西。确保重新启动服务器,使其生效。
OpenURI::Buffer.send :remove_const, 'StringMax'
OpenURI::Buffer.const_set 'StringMax', 0
然后您可以通过网址上传
def upload_file(filename, url)
s3 = Aws::S3::Resource.new(region:'us-west-2')
obj = s3.bucket(bucket_name).object(filename) # make sure your filename has an extension (.jpg for example)
File.open(open(url), 'rb') do |file|
obj.put(body: file)
end
end