从Ruby中的图像url将图像上传到AWS?
答
A-Ha!我已经有了答案,但发现这很难找出...
不幸的是,我没有先从源URL下载有问题的文件,我无法完成此任务。
因此,这里是我如何上传产品图片:
首先设置你的S3存储在app /配置/初始化/ aws.rb
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'])
然后我创建的应用程序/工人/ 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)
这正是我如何通过我们可以控制的产品和image_urls来挖掘整个网站的种子。