Sha256: 2e07db64d33f587a407e14cdb1f4c8429bc36cfc5af3d082e2a732d6faf6c882

Contents?: true

Size: 1.36 KB

Versions: 5

Compression:

Stored size: 1.36 KB

Contents

require 'net/http'
require 'uri'
require 'ruby-progressbar'

module OrmDev
  class DownloadUtil
    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

    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
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ormdev-0.2.3 lib/ormdev/source/util/download_util.rb
ormdev-0.2.2 lib/ormdev/source/util/download_util.rb
ormdev-0.2.1 lib/ormdev/source/util/download_util.rb
ormdev-0.2.0 lib/ormdev/source/util/download_util.rb
ormdev-0.1.8 lib/ormdev/source/util/download_util.rb