Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Created June 27, 2010 13:55
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save Burgestrand/454926 to your computer and use it in GitHub Desktop.
Save Burgestrand/454926 to your computer and use it in GitHub Desktop.
Ruby HTTP file download with progress measurement
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
@rdp
Copy link

rdp commented Jul 12, 2012

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...

@Burgestrand
Copy link
Author

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.

@rdp
Copy link

rdp commented Jul 16, 2012

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).

@Barkhat26
Copy link

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