如何通过HTTP下载二进制文件? [英] How do I download a binary file over HTTP?

查看:244
本文介绍了如何通过HTTP下载二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Ruby下载和保存二进制文件?

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

URL是 http://somedomain.net/flv /sample/sample.flv

我在Windows平台上,我不想运行任何外部程序。

I am on the Windows 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`

可能您正在寻找:

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."

编辑:更改。谢谢。

编辑2:下载时保存文件的一部分的解决方案:

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

这篇关于如何通过HTTP下载二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆