1
我有一個來自圖像標記的源網址,我想將該圖像上傳到我的S3存儲桶。我將如何做到這一點? A-Ha!從Ruby中的圖像url將圖像上傳到AWS?
我有一個來自圖像標記的源網址,我想將該圖像上傳到我的S3存儲桶。我將如何做到這一點? A-Ha!從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來挖掘整個網站的種子。