-
-
Save Thermatix/3a8138baf705b55a565c to your computer and use it in GitHub Desktop.
Ruby Net:HTTP chunked transfer
This file contains 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 'uri' | |
require 'net/http' | |
class Chunked | |
def initialize(data, chunk_size) | |
@size = chunk_size | |
if data.respond_to? :read | |
@file = data | |
end | |
end | |
def read(foo) | |
if @file | |
@file.read(@size) | |
end | |
end | |
def eof! | |
@file.eof! | |
end | |
def eof? | |
@file.eof? | |
end | |
end | |
#in sinatra | |
post '/image' do | |
cross_origin | |
name = params[:name] | |
my_file = params[:my_file] | |
unless params[:my_file] && (tmpfile = params[:my_file][:tempfile]) | |
@error = "No file selected" | |
return haml(:upload) | |
end | |
parsed = URI::parse(@storage_url) | |
conn = Net::HTTP.new(parsed.host, parsed.port) | |
fp = File::open(tmpfile) | |
parsed.path += '/foo/test.txt' | |
chunked = Chunked.new(fp, 5) | |
request = Net::HTTP::Put.new parsed.request_uri, {'x-auth-token' => @auth_token, 'Transfer-Encoding' => 'chunked', 'content-type' => 'text/plain'} | |
request.body_stream = chunked | |
conn.start do |http| | |
http.request(request) | |
end | |
fp.close | |
"Upload complete\n" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment