rubydownload

How do I download a binary file over HTTP?


How do I download and save a binary file over HTTP using Ruby?

The URL is http://somedomain.net/flv/sample/sample.flv.

I am on the Windows platform and I would prefer not to run any external program.


Solution

  • 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'
    # Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
    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."
    

    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