7

i would like to create a Rails controller that download a serie of jpg files from the web and directly write them into database as binary (I am not trying to do an upload form)

Any clue on the way to do that ?

Thank you

Edit : Here is some code I already wrote using attachment-fu gem :

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 an "undefined method `content_type' for #" error

John Topley
  • 113,588
  • 46
  • 195
  • 237
Chris
  • 2,744
  • 3
  • 24
  • 39

1 Answers1

6

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

UPDATE:

Attachment_fu does not accept the raw bytes, it needs a "file-like" object. Use this example of a LocalFile along with the code below to dump the image into a temp file then send that 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
  }
marcgg
  • 65,020
  • 52
  • 178
  • 231
Jonathan Julian
  • 12,163
  • 2
  • 42
  • 48
  • Thank you, I already tried that with another gem, but did not succeed. See my sample code above – Chris Apr 03 '10 at 15:08
  • `content_type` is undefined because attachement_fu expects a file, not a stream of bytes. I've updated my answer with some code. – Jonathan Julian Apr 03 '10 at 16:03