class OrmDev::DownloadUtil

Public Class Methods

download(url, save_path, title = '文件') click to toggle source
# File lib/ormdev/source/util/download_util.rb, line 7
def self.download(url, save_path, title = '文件')
  uri = URI(url)
  Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Get.new uri
    http.request request do |response|
      file_size = response['content-length'].to_i
      pbar = ProgressBar.create(:title => title, :starting_at => 0, :total => file_size, :format => '%a |%b>>%i| %p%% %t')
      amount_downloaded = 0
      File.open save_path, 'wb' do |io| # 'b' opens the file in binary mode
        response.read_body do |chunk|
          io.write chunk
          amount_downloaded += chunk.size
          pbar.progress=amount_downloaded
          # puts "%.2f%" % (amount_downloaded.to_f / file_size * 100)
        end
      end
      pbar.finish
    end
  end
end
download_cp(path, save_dir, save_name, title = '文件') click to toggle source
# File lib/ormdev/source/util/download_util.rb, line 28
def self.download_cp(path, save_dir, save_name, title = '文件')
  save_path = File.join(save_dir, save_name)
  FileUtils.mkdir_p(save_dir) unless Dir.exist?(save_dir)
  FileUtils.rm_rf(save_path) if Dir.exist?(save_path)
  if (path.downcase.start_with?('http://') || path.downcase.start_with?('https://')) then
    ORM::DownloadUtil.download(path, save_path, title )
  else
    FileUtils.cp( path, save_path )
  end
end