views:

614

answers:

2

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.

+5  A: 

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
Dejw
@Dejw:works nicely.I got confused by resp.body. Please change `Net::HTTP.start("http://somedomain.net/")` in your code to `Net::HTTP.start("somedomain.net")` otherwise it won't work. Thank you for your help
Radek
A: 

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.

Arkku