Title: ruby download progress Fromvkill'blog 何永鹏 Time:Tue, 23 Jun 2009 09:29:03 +0000 Author:vkill URL:http://blog.vkill.net/read.php/133.htm Content: 采用的是分片下载,应该有更好的方法,不过大概原理都是一样的 #!/usr/bin/env ruby # # ruby Download progress # by:vkill 23/6/2009 # require 'net/http' require 'uri' url = "http://127.0.0.1/upd/vdf/antivir3.vdf.gz" u = URI.parse(url) fileName = File.basename(u.path) http = Net::HTTP.new(u.host,u.port) req = Net::HTTP::Head.new(u.path) resp = http.request(req) totalLenght = resp["Content-Length"].to_i partLenght = 20480 if totalLenght > 10240000 puts "request downing file size GTR 10M, program quit!!!" exit end downing = Thread.new { $transLenght = 0 $data = "" while $transLenght <= totalLenght do lenghts = $transLenght lenghte = $transLenght + partLenght - 1 lenghte = totalLenght if lenghte > totalLenght header = {"Range" => "bytes=#{lenghts}-#{lenghte}"} req = Net::HTTP::Get.new(u.path,header) if (resp = http.request(req) rescue false) == false self.kill else $transLenght += partLenght $data = $data.concat(resp.body) end end } while downing.status == "run" or downing.status == "sleep" do printf "\rdowning #{fileName}...[#{totalLenght}bytes] #{$transLenght/(totalLenght/100)}%" sleep 0.5 end if totalLenght == $data.size printf "\rdowning #{fileName}...[#{totalLenght}bytes] 100%\n" f = File.new(fileName,"wb+") f << $data f.flush f.close else printf "...Err\n" end case downing.status when false puts "downing normally quit" when nil puts "downing unnormally quit" else puts "downing nuknow quit" end Generated by Bo-blog 2.1.1 Release