I can do File.size(path)
to get the size of a file in bytes. How do I get the size of an HTTP response without writing it to a tempfile?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Call .size
on the thing you'd write to the tempfile?
Or if its over HTTP, you might be able to get the content length from headers alone. Example:
require 'net/http'
response = nil
# Just get headers
Net::HTTP.start('stackoverflow.com', 80) do |http|
response = http.head('/')
end
puts response.content_length
# Get the entire response
Net::HTTP.start('stackoverflow.com', 80) do |http|
response = http.get('/')
end
puts response.body.size
Note that if the server does not provide the content length (often the case for dynamic content), then response.content_length
will be nil
.