Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Created June 27, 2010 13:55
Show Gist options
  • Select an option

  • Save Burgestrand/454926 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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
Copy Markdown

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