Last active
January 1, 2016 04:49
-
-
Save c4pt0r/8094317 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
import os | |
import sys | |
import tornado.web | |
import tornado.ioloop | |
import json | |
import random, string | |
raw_file_path = None | |
meta_data_path = None | |
def randomword(length): | |
return ''.join(random.choice(string.lowercase) for i in range(length)) | |
def init(): | |
global raw_file_path, meta_data_path | |
raw_file_path = os.path.dirname(os.path.abspath(__file__)) + './.files/' | |
meta_data_path = os.path.dirname(os.path.abspath(__file__)) + './.meta/' | |
try: | |
os.mkdir(raw_file_path) | |
os.mkdir(meta_data_path) | |
except: | |
pass | |
def key_exists(key): | |
if os.path.exists(raw_file_path + key + '.raw') and os.path.exists(meta_data_path + key + '.meta'): | |
return True | |
return False | |
class UploadHandler(tornado.web.RequestHandler): | |
def get(self): | |
pass | |
def post(self): | |
for k in self.request.files.keys(): | |
for f in self.request.files[k]: | |
raw_name = f['filename'] | |
key = randomword(8) | |
fp = open(raw_file_path + key + '.raw', 'wb') | |
fp.write(f['body']) | |
fp.close() | |
fp_meta = open(meta_data_path + key + '.meta', 'w') | |
content = json.dumps({'filename': raw_name, 'key': key, 'size': len(f['body'])}) | |
fp_meta.write(content) | |
fp_meta.close() | |
self.finish(self.request.host + '/' + key + '\n') | |
return | |
class FetchHandler(tornado.web.RequestHandler): | |
def get(self, **params): | |
key = params['key'] | |
if not key_exists(key): | |
self.set_status(404) | |
return | |
print meta_data_path | |
with open(meta_data_path + key + '.meta', 'r') as meta_fp: | |
meta = json.loads(meta_fp.read()) | |
fname = meta['filename'] | |
fsize = meta['size'] | |
with open(raw_file_path + key + '.raw', 'rb') as fp: | |
self.set_header('Content-Type', 'application/octet-stream') | |
self.set_header('Content-Disposition', 'attachment; filename="%s"' % fname) | |
self.set_header('Content-Length', str(fsize)) | |
self.write(fp.read()) | |
application = tornado.web.Application([ | |
(r"/", UploadHandler), | |
(r"/(?P<key>[^\/]+)", FetchHandler), | |
], debug=True) | |
if __name__ == '__main__': | |
init() | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment