I only need to download the first few kilobytes of a file via HTTP.
I tried
require 'open-uri'
url = 'http://example.com/big-file.dat'
file = open(url)
content = file.read(limit)
But it actually downloads the full file.
I only need to download the first few kilobytes of a file via HTTP.
I tried
require 'open-uri'
url = 'http://example.com/big-file.dat'
file = open(url)
content = file.read(limit)
But it actually downloads the full file.
Check out "OpenURI returns two different objects". You might be able to abuse the methods in there to interrupt downloading/throw away the rest of the result after a preset limit.
This seems to work when using sockets:
I'm curious if there is a "ruby way".
This is an old thread, but it's still a question that seems mostly unanswered according to my research. Here's a solution I came up with by monkey-patching Net::HTTP a bit:
The rescue catches the IOError that's thrown when you call HTTP.finish prematurely.
FYI, the socket within the
HTTPResponse
object isn't a trueIO
object (it's an internal class calledBufferedIO
), but it's pretty easy to monkey-patch that, too, to mimic theIO
methods you need. For example, another library I was using (exifr) needed thereadchar
method, which was easy to add: