1

我正在开发一个必须上传 zip 文件的应用程序。zip 文件基本上是一个静态网站,因此它有很多文件和几个子目录。我已经玩了一段时间的 ruby​​zip gem 并且不知道如何简单地从中提取文件。关于我可以在哪里阅读一些示例的任何指示?我相信以前有人遇到过这个问题。rubyzip 的文档不是很好,所以我希望有人能给我一些指示。

4

1 回答 1

1

给你,一个超级神奇的多线程 zip-to-S3 上传器,我根本没有测试过 - 发疯!看来我晚了三年。

class S3ZipUploader

  require 'thread'
  require 'thwait'
  require 'find'

  attr_reader *%i{ bucket s3 zip failed_uploads }

  def initialize(zipfilepath, mys3creds)
    # next 4 lines are important
    @s3 = AWS::S3.new(access_key_id: mys3creds[Rails.env]['aws_access_key'],
                         secret_access_key: mys3creds[Rails.env]['aws_secret_access_key'],
                         region: 'us-west-2')
    @bucket = @s3.buckets[ mys3creds[Rails.env]['bucket'] ]

    @failed_uploads = []
    @zip = Zip::File.open(zipfilepath)

  end


  def upload_zip_contents

    rootpath = "mypath/"

    desired_threads = 10
    total_entries = zip.entries.count
    slice_size = (total_entries / desired_threats).ceil
    threads = []
    zip.entries.each_slice(slice_size) do |e_arr|
      threads << Thread.new do |et|
        e_arr.each do |e|
          result = upload_to_s3(rootpath + e.name, e.get_input_stream.read) 
          if !result
            @failed_uploads << {name: e.name, entry: e, error: err}
          end
        end
      end
    end
    ThreadsWait.all_waits(*threads)
  end

  def upload_file_to_s3(filedata,path, rewrite_basepath)
    retries = 0
    success = false
    while !success && retries < 3
      success = begin
        obj = bucket.objects[path]
        obj.write(Pathname.new(outputhtml))
        obj.acl = :public_read
        success = true
      rescue
        retries += 1
        success = false
      end
    end
    return success
  end

end

uploader = S3ZipUploader.new("/path/to/myzip.zip", MYS3CREDS)
uploader.upload_zip_contents
于 2016-04-18T02:41:43.443 回答