在下载和计算已经下载的数量之前获取文件大小(http + ruby​​)

任何人都可以帮助我

  • 开始下载之前获取文件大小
  • 显示已下载了多少

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

使用request_head方法。 像这样

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

file_size将以字节为单位。

请按照以下两个链接获取更多信息。

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

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

所以即使使用进度条我也能使它工作….

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

HTTP Content-Length响应头中提供了文件大小。 如果不存在,则无法执行任何操作。 要计算%,就像小学数学一样(部分/总计* 100)。

这里是下载之前获取文件详细信息的完整代码

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