任何人都可以帮我
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."
答案 0 :(得分:21)
使用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
答案 1 :(得分: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."
答案 2 :(得分:3)
文件大小在HTTP Content-Length
响应标头中可用。如果不存在,则无法执行任何操作。要计算%,就像小学数学一样(部分/总计* 100)。
答案 3 :(得分: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}" }