Created
September 14, 2015 18:51
-
-
Save trevorrowe/2bc056ecb21a57f36ae5 to your computer and use it in GitHub Desktop.
Tracking progress of a file upload using v2 of the aws-sdk gem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'aws-sdk' | |
require 'pathname' | |
class ProgressIO | |
def initialize(io) | |
@io = io | |
@bytes_read = 0 | |
@listeners = [] | |
end | |
def read(bytes, output_buffer = nil) | |
signal(bytes) | |
@io.read(bytes, output_buffer) | |
end | |
def rewind(*args) | |
@bytes_read = 0 | |
signal(0) | |
@io.rewind(*args) | |
end | |
def size | |
@io.size | |
end | |
def listen(&block) | |
@listeners << block | |
end | |
private | |
def signal(bytes) | |
@bytes_read += bytes | |
@listeners.each do |callback| | |
callback.call(@bytes_read, size) | |
end | |
end | |
end | |
s3 = Aws::S3::Client.new | |
s3.handle(step: :sign, priority: 0) do |context| | |
progress = ProgressIO.new(context.http_request.body) | |
progress.listen do |bytes_read, total| | |
puts "READ #{bytes_read} / #{total}" | |
end | |
context.http_request.body = progress | |
@handler.call(context) | |
end | |
File.open('./large-file.txt', 'rb') do |file| | |
s3.put_object({ | |
bucket: 'aws-sdk', | |
key: File.basename(file), | |
body: file, | |
}) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment