How can I download a file from a URL and save it in Rails?

Alok Swain picture Alok Swain · Mar 25, 2010 · Viewed 137.8k times · Source

I have a URL to an image which i want to save locally, so that I can use Paperclip to produce a thumbnail for my application. What's the best way to download and save the image? (I looked into ruby file handling but did not come across anything.)

Answer

Levi picture Levi · Mar 25, 2010

Try this:

require 'open-uri'
open('image.png', 'wb') do |file|
  file << open('http://example.com/image.png').read
end