Created
March 16, 2011 02:25
-
-
Save chrisrobinson/871903 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
require 'net/http' | |
require 'uri' | |
BLOCK_SIZE = 1048576 # bytes | |
URL = "http://localhost:8000/upload" | |
filename = ARGV[0] | |
f = File.open(filename, 'rb') | |
file_size = f.stat.size | |
session_id = (1..20).map { rand 10 }.join | |
last_block = file_size % BLOCK_SIZE | |
block_count = (file_size / BLOCK_SIZE) | |
block_count += 1 unless last_block.zero? | |
puts "Uploading \"#{filename}\" as #{block_count} pieces of #{(file_size.to_f/block_count).ceil} bytes each" | |
block_count.times do |i| | |
body = f.read(BLOCK_SIZE) | |
block_start = BLOCK_SIZE * i | |
block_end = block_start + BLOCK_SIZE - 1 | |
block_end = file_size if block_end > file_size | |
headers = {'Content-Type' => 'application/octet-stream', | |
'Content-Disposition' => "attachment; filename=\"#{File.basename(filename)}\"", | |
'X-Content-Range' => "bytes #{block_start}-#{block_end}/#{file_size}", | |
'X-Session-ID' => session_id} | |
puts "Uploading chunk #{i+1}: #{headers['X-Content-Range']}" | |
uri = URI.parse(URL) | |
http = Net::HTTP.new(uri.host, uri.port) | |
response = http.post(uri.path, body, headers) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment