ruby中下载文件的几种方法

记录几种常见的下载文件的办法
更新于: 2021-12-19 12:57:29

利用 shell 命令 curl/wget

下载并重命名

system "curl -L http://sourceforge.net/projects/sofastatistics/files/latest/download?source=files -o foo.deb"

利用 url-open

require "open-uri"

open("https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/test.original.jpg") do |image|
  File.open("./test.jpg", "wb") do |file|
    file.write(image.read)
  end
end

利用第三方包

require "down"
require "fileutils"

tempfile = Down.download("https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/test.original.jpg")
FileUtils.mv(tempfile.path, "./#{tempfile.original_filename}")
Down.download(
  "https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/test.original.jpg",
  max_redirects: 5,
  max_size: 5 * 1024 * 1024
)

自定义 download 方法

注意下面的代码在 https 下有问题,需要自己解决

require "open-uri"
require "fileutils"

def download(url, path)
  case io = open(url)
  when StringIO then File.open(path, 'w') { |f| f.write(io.read) }
  when Tempfile then io.close; FileUtils.mv(io.path, path)
  end
end

参考