如何上传zip文件并解压缩到s3?

时间:2013-04-15 13:18:36

标签: ruby amazon-s3 zip rubyzip

我正在开发一个我必须上传zip文件的应用程序。 zip文件基本上是一个静态网站,因此它有许多文件和几个子目录。我一直在玩rubyzip gem一段时间,无法弄清楚如何从中提取文件。关于我可以在一些例子中阅读的任何指示?我相信有人之前已经遇到过这个问题。 rubyzip的文档不是很好,所以我希望有人可以给我一些指示。

1 个答案:

答案 0 :(得分:0)

在这里,一个超级神奇的多线程拉链到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