Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save webmanarmy/346263 to your computer and use it in GitHub Desktop.
Save webmanarmy/346263 to your computer and use it in GitHub Desktop.

Revisions

  1. webmanarmy created this gist Mar 27, 2010.
    32 changes: 32 additions & 0 deletions Simple File Upload with Tornaod Web Server
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    import tornado.httpserver, tornado.ioloop, tornado.options, tornado.web, os.path
    from tornado.options import define, options

    define("port", default=8888, help="run on the given port", type=int)

    class Application(tornado.web.Application):
    def __init__(self):
    handlers = [
    (r"/", HomeHandler),
    (r"/upload", UploadHandler)
    ]
    tornado.web.Application.__init__(self, handlers)

    class HomeHandler(tornado.web.RequestHandler):
    def get(self):
    self.finish('<html><form enctype="multipart/form-data" action="/upload" method="post">Upload File: <input type="file" name="file1" /><input type="submit" value="upload" />');

    class UploadHandler(tornado.web.RequestHandler):
    def post(self):
    file1 = self.request.files['file1'][0]
    # now you can do what you want with the data, we will just save the file to an uploads folder
    output_file = open("uploads/" + file1['filename'], 'w')
    output_file.write(file1['body'])
    self.finish('Your file has been uploaded')

    def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

    if __name__ == "__main__":
    main()