Radek Radek - 2 months ago 7
Ruby Question

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

Answer

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