DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Terry has posted 2 posts at DZone. View Full User Profile

How To Download Files With Ruby

08.25.2006
| 68383 views |
  • submit to reddit
        // Note: the "b" in "wb" in the open method may not be needed in
// non-Windows environments.  In Windows it indicates that you're writing
// binary information.  You probably won't need it for downloading straight text
// or html either.

require 'net/http'

Net::HTTP.start("static.flickr.com") { |http|
  resp = http.get("/92/218926700_ecedc5fef7_o.jpg")
  open("fun.jpg", "wb") { |file|
    file.write(resp.body)
   }
}
puts "Yay!!"
    

Comments

Snippets Manager replied on Sat, 2009/05/09 - 2:35am

Note that this will *not* follow redirection by default. See http://www.ensta.fr/~diam/ruby/online/ruby-doc-stdlib/libdoc/net/http/rdoc/index.html

Snippets Manager replied on Tue, 2011/07/19 - 4:28am

If you want to download images from web pege, you can use ruby gem image_downloader require 'rubygems' require 'image_downloader' downloader = ImageDownloader::Process.new('www.test.com','img_dir/') downloader.parse(:any_looks_like_image => true) downloader.download()

Snippets Manager replied on Sat, 2009/05/09 - 2:35am

or use open uri def download full_url, to_here require 'open-uri' writeOut = open(to_here, "wb") writeOut.write(open(full_url).read) writeOut.close end

Terry Donaghe replied on Fri, 2006/08/25 - 3:42pm

For more information see my post at rubynoob.com: http://www.rubynoob.com/articles/2006/08/21/how-to-download-files-with-a-ruby-script