Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file size before downloading & counting how much already downloaded (http+ruby)

Can anybody help me to

  • get the file size before I start downloading
  • display how much % was already downloaded

.

require 'net/http'
require 'uri'

url = "http://www.onalllevels.com/2009-12-02TheYangShow_Squidoo_Part 1.flv"

url_base = url.split('/')[2]
url_path = '/'+url.split('/')[3..-1].join('/')

Net::HTTP.start(url_base) do |http|
  resp = http.get(URI.escape(url_path))
  open("test.file", "wb") do |file|
    file.write(resp.body)
  end
end
puts "Done."
like image 997
Radek Avatar asked Feb 20 '10 04:02

Radek


1 Answers

Use the request_head method. Like this

response = http.request_head('http://www.example.com/remote-file.ext')
file_size = response['content-length']

The file_size will be in bytes.

Follow these two links for more info.

http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html#M000695

http://curl.haxx.se/mail/archive-2002-07/0070.html

like image 162
GeekTantra Avatar answered Nov 06 '22 21:11

GeekTantra