在下载文件之前获取文件大小并计算已下载量(http+ruby)

13

请问有谁能帮助我:

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

.

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."
4个回答

25

@GeekTantra:response ['content-length'] 运行良好。谢谢。我试图显示“response”,但没有任何反应。现在的大问题是我如何计算已经下载了多少.... - Radek
不可能的。设置“Content-Length”标头是服务器的责任。如果“http://www.onalllevels.com”在您的控制下,请修复它,否则请尝试联系他们并要求他们进行修复。 - BalusC
我被告知服务器不必提供内容长度http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html使用SHOULD发送... - Radek
1
如果使用分块编码,Content-Length不是会丢失吗? - Zepplock

4

所以我让它即使带有进度条也能正常工作...

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

文件大小可以在HTTP响应头中的Content-Length字段中获取。如果不存在该字段,则无法进行任何操作。要计算百分比,只需进行小学数学运算如 (部分/总数 * 100)。


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接