5

What's the more straightforward way to download a file from given URL and uploading it immediately to Amazon S3 (+ save into database some information about the file, like name, size etc)?

Right now, I am not using Paperclip neither Carrierwave.

Thank you

user984621
  • 46,344
  • 73
  • 224
  • 412

1 Answers1

9

Straightforward:

require 'open-uri'
require 's3'

amazon = S3::Service.new(access_key_id: 'KEY', secret_access_key: 'KEY')
bucket = amazon.buckets.find('image_storage')
url = 'http://www.example.com/url'
download = open(url)

file = bucket.objects.build('image.png')
file.content = (File.read download)

if file.save
  # Make a new ActiveRecord::Base class for this
  LogFile.create(size: download.size, type: download.type, name: url)
end

https://github.com/qoobaa/s3

ichigolas
  • 7,595
  • 27
  • 50
  • where do you write this ? – 2ueenO Dec 10 '13 at 15:46
  • In a plain text file, then run it with `$ ruby file.rb` (?) – ichigolas Dec 10 '13 at 17:52
  • yes but i'm really interesting by your solution, and i would like to insert it in my website to store pictures from aviary. I have created another question : [Save a picture in S3 from a temporary URL](http://stackoverflow.com/questions/20500057/save-a-picture-in-s3-from-a-temporary-url) – 2ueenO Dec 10 '13 at 18:09
  • You can put this code in any controller action, or wherever you see fit. For example, you could make a form to submit a url to an action, and the take it as a parameter for replacing the `url` variable – ichigolas Dec 10 '13 at 18:47