require 'net/http'
File.write(file_name, Net::HTTP.get(URI.parse(url)))
我想向用户展示这里发生了什么,比如进度,因为文件的大小可能很大。但是只有用户可能感兴趣的信息,而不是所有的调试信息。
Net::HTTP.get
有这样的能力吗?
最佳答案
您可以在这里找到相关信息:http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Streaming+Response+Bodies
文档中用于此类事情的示例片段是:
require 'net/http'
uri = URI("http://apps.sfgov.org/datafiles/view.php?file=sfgis/citylots.zip")
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new uri
http.request request do |response|
file_size = response['content-length'].to_i
amount_downloaded = 0
open 'large_file', 'wb' do |io| # 'b' opens the file in binary mode
response.read_body do |chunk|
io.write chunk
amount_downloaded += chunk.size
puts "%.2f%" % (amount_downloaded.to_f / file_size * 100)
end
end
end
end
关于ruby - Net::HTTP.get 显示进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26878587/