views:

266

answers:

3

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."
A: 

The file size is available in the HTTP Content-Length response header. If it is not present, you can't do anything. To calculate the %, just do the primary school math like (part/total * 100).

BalusC
+3  A: 

Hi,

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

GeekTantra
@GeekTantra: response['content-length'] works fine.Thank you.I was trying to display 'response' and it gave me nothing. The big question now is how I can count what was already downloaded....
Radek
That's not possible. It's the server responsibility to set the `Content-Length` header. If `http://www.onalllevels.com` is under your control, fix it, else try to contact them and ask them to fix.
BalusC
I was told that server `doesn`t have to provide` the `content-length` http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html use word SHOULD send ...
Radek
Isn't Content-Length missing if chunk encoding is used?
Zepplock
A: 

so I made it work even with the progress bar ....

require 'net/http'
require 'uri'
require 'progressbar'

url = "url with some file"


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

Net::HTTP.start(url_base) do |http|
  response = http.request_head(URI.escape(url_path))
  ProgressBar#format_arguments=[:title, :percentage, :bar, :stat_for_file_transfer]
  pbar = ProgressBar.new("file name:", response['content-length'].to_i)
  File.open("test.file", 'w') {|f|
    http.get(URI.escape(url_path)) do |str|
      f.write str
  @counter += str.length 
  pbar.set(@counter)
    end
   }
end
pbar.finish
puts "Done."
Radek