Created
June 27, 2010 13:55
-
-
Save Burgestrand/454926 to your computer and use it in GitHub Desktop.
Ruby HTTP file download with progress measurement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'uri' | |
def download(url) | |
Thread.new do | |
thread = Thread.current | |
body = thread[:body] = [] | |
url = URI.parse url | |
Net::HTTP.new(url.host, url.port).request_get(url.path) do |response| | |
length = thread[:length] = response['Content-Length'].to_i | |
response.read_body do |fragment| | |
body << fragment | |
thread[:done] = (thread[:done] || 0) + fragment.length | |
thread[:progress] = thread[:done].quo(length) * 100 | |
end | |
end | |
end | |
end | |
thread = download 'http://caesar.acc.umu.se/mirror/ubuntu-releases/10.04/ubuntu-10.04-desktop-i386.iso' | |
puts "%.2f%%" % thread[:progress].to_f until thread.join 1 |
Wow, I had forgotten I even wrote this. :D
I’m sure the rubyinstaller way is better; I believe I wrote this example in just a few minutes. It hasn’t been tested much at all.
Interestingly, it appears that you can use open-uri to have a "callback" as well: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/open-uri/rdoc/OpenURI/OpenRead.html :progress_proc if that helps any followers. (open-uri for instance followers redirects, whereas net/http doesn't, so may be a better fit).
How to save the file on the disk?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
looks like rubyinstaller does something similar: https://github.com/oneclick/rubyinstaller/blob/master/rake/contrib/uri_ext.rb#L234 though looks like you may be able to do something like response.content_length to simplify, but anyway this seems to be a common way to do it...