Get file size before downloading & counting how mu

2019-04-21 20:29发布

问题:

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

回答1:

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



回答2:

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


回答3:

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



回答4:

Here the full code to get file details before download

require 'net/http'
response = nil
uri = URI('http://hero.com/abc.mp4')
Net::HTTP.start(uri.host, uri.port) do |http|
  response = http.head(uri)
end
response.header.each_header {|key,value| puts "#{key} = #{value}" }