简体   繁体   中英

How do you upload a zip file and unzip to s3?

I am working on an application where I have to upload a zip file. The zip file is basically a static website so it has many files and a couple subdirectories. I have been playing with the rubyzip gem for a while now and can not figure out how to simply extract the files from it. Any pointers on where I can read up on some examples? I am sure someone has ran in to this problem before. the documentation for rubyzip is not very good so I am hoping someone can give me some pointers.

Here you go, one super magical multithreaded zip-to-S3 uploader which I haven't tested at all - go nuts! Looks like I'm three years too late though.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM