Rails: how to download a file from http and save it to the database

I would like to create a Rails controller that downloads a series of jpg files from the Internet and directly writes them to the database as binary (I'm not trying to download a form)

Any clue on how to do this?

thanks

Edit: Here is the code I already wrote using the -fu gem prefix:

http = Net::HTTP.new('awebsite', 443) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.start() { |http| req = Net::HTTP::Get.new("image.jpg") req.basic_auth login, password response = http.request(req) attachment = Attachment.new(:uploaded_data => response.body) attachement.save } 

And I get the undefined method `content_type 'for #" error

+6
ruby ruby-on-rails
source share
1 answer

Use open-url (in Ruby stdlib) to capture files, then use a gem like paperclip to save them in db as attachments to your models.

UPDATE:

Attachment_fu does not accept raw bytes, it needs a "file-like" object. Use this LocalFile example along with the code below to upload the image to a temporary file and then send it to your model.

  http = Net::HTTP.new('www.google.com') http.start() { |http| req = Net::HTTP::Get.new("/intl/en_ALL/images/srpr/logo1w.png") response = http.request(req) tempfile = Tempfile.new('logo1w.png') File.open(tempfile.path,'w') do |f| f.write response.body end attachment = Attachment.new(:uploaded_data => LocalFile.new(tempfile.path)) attachement.save } 
+6
source

All Articles