Created
January 20, 2012 20:43
-
-
Save joaodrp/1649452 to your computer and use it in GitHub Desktop.
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
module Backend | |
CHUNKSIZE = 65536 | |
def self.save(tmp_file, new_file) | |
md5 = Digest::MD5.new | |
STDERR.puts "COPYING!!" | |
open(tmp_file, "rb") do |tmp| | |
open(new_file, "wb") do |new| | |
until tmp.eof? | |
chunk = tmp.read(CHUNKSIZE) | |
new << chunk | |
md5.update chunk | |
end | |
end | |
end | |
md5.hexdigest | |
end | |
end |
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
class PostImage < Goliath::API | |
use Goliath::Rack::Render, 'json' | |
def on_headers(env, headers) | |
env['headers'] = headers | |
end | |
# receive large file in chunks and use a tempfile as buffer | |
def on_body(env, data) | |
env['body'] ||= Tempfile.open('tmp-image', encoding: 'ascii-8bit') | |
env['body'] << data | |
end | |
def response(env) | |
id = pull_metadata_from_custom_headers(env['headers'])[:_id] | |
body = env['body'] | |
begin | |
meta = upload_and_update(id, body) | |
# 400 rescue example only, many more not included to make this gist slim | |
rescue => e | |
return [400, {}, {message: e.message}] | |
ensure | |
body.unlink | |
end unless body.nil? | |
[200, {}, {image: meta}] | |
end | |
# Update image status and launch upload | |
def upload_and_update(id, body) | |
db.put_image(id, status: 'uploading') | |
checksum = do_upload(body) | |
# only after complete update, update its meta on db | |
db.put_image(id, status: 'available', checksum: checksum) | |
end | |
# Upload of received file (in this case, its just a copy to other hd location) | |
def do_upload(body) | |
new = File.open('some file') | |
Backend.save(body, new) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment