简体   繁体   English

Net :: HTTP.get显示进度

[英]Net::HTTP.get show progress

require 'net/http'

File.write(file_name, Net::HTTP.get(URI.parse(url)))

I want to show to the user what's happening here, something like progress because the size of a file can be big. 我想告诉用户这里发生了什么,比如进度,因为文件的大小可能很大。 But only the information the user can be interested in, not all the debug information. 但是只有用户可能感兴趣的信息,而不是所有调试信息。

Does Net::HTTP.get have such an ability? Net::HTTP.get有这种能力吗?

You can find information on that here: http://ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Streaming+Response+Bodies 您可以在此处找到有关此信息: http : //ruby-doc.org/stdlib-2.1.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net :: HTTP-label-Streaming+Response +机构

The example snippet used in the docs for just such a thing is: 在文档中使用的示例片段就是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM