Tornado – File Uploads

Quite often we’re in need of providing file upload mechanism on our website. Be it logs management or user profile management, support for file upload is a must. This blog describes how uploads be achieved with Tornado web server.

Example code:

import tornado
import tornado.ioloop
import tornado.web
import os, uuid
__UPLOADS__ = "uploads/"
class Userform(tornado.web.RequestHandler):
def get(self):
class Upload(tornado.web.RequestHandler):
def post(self):
fileinfo = self.request.files['filearg'][0]
print "fileinfo is", fileinfo
fname = fileinfo['filename']
extn = os.path.splitext(fname)[1]
cname = str(uuid.uuid4()) + extn
fh = open(__UPLOADS__ + cname, 'w')
self.finish(cname + " is uploaded!! Check %s folder" %__UPLOADS__)
application = tornado.web.Application([
(r"/", Userform),
(r"/upload", Upload),
], debug=True)
if __name__ == "__main__":

In this code snippet;

  • When user browses to http://localhost:8888/, he is presented with file upload form (code below)
  • On browsing and selecting the appropriate file, the user clicks on upload
  • The file gets uploaded and the user gets a message with filename & the uploaded location

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Upload Form</title>
<p><h1>Select & Upload</h1></p>
<form enctype="multipart/form-data" action="/upload" method="post">
File: <input type="file" name="filearg" />
<br />
<br />
<input type="submit" value="upload" />

In the upload form, its important to note the usage of below tags for file uploads:

  • enctype=”multipart/form-data”
  • input type=”file

As a side note, if you print fileinfo variable, you would observe a dictionary with contents and meta-data of file being uploaded

fileinfo is {'body': 'This is a file upload test for Tornado!!\n', 'content_type': u'application/octet-stream', 'filename': u'fileuploadtest'}

2 thoughts on “Tornado – File Uploads

  1. Hi. I’ve got error 405 Method not allowed. Could you please help me, I am a beginner.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.