How do I
- download and
save
a binary file over HTTP using Ruby?
let's say for example the url is http://somedomain.net/flv/sample/sample.flv
I am on win platform and I would prefer not to run any external program.
How do I
save
a binary file over HTTP using Ruby?
let's say for example the url is http://somedomain.net/flv/sample/sample.flv
I am on win platform and I would prefer not to run any external program.
The simplest way is (the platform-specific solution):
#!/usr/bin/env ruby
`wget http://somedomain.net/flv/sample/sample.flv`
Probably You are searching for:
require 'net/http'
Net::HTTP.start("somedomain.net/") do |http|
resp = http.get("/flv/sample/sample.flv")
open("sample.flv", "wb") do |file|
file.write(resp.body)
end
end
puts "Done."
Edit: Changed. Thank You.
Edit2: The solution which saves part of a file while downloading:
# instead of http.get
f = open('sample.flv')
begin
http.request_get('/sample.flv') do |resp|
resp.read_body do |segment|
f.write(segment)
end
end
ensure
f.close()
end
Example 3 in the Ruby's net/http documentation shows how to download a document over HTTP, and to output the file instead of just loading it into memory, substitute puts with a binary write to a file, e.g. as shown in Dejw's answer.
More complex cases are shown further down in the same document.