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:
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 tornado | |
import tornado.ioloop | |
import tornado.web | |
import os, uuid | |
__UPLOADS__ = "uploads/" | |
class Userform(tornado.web.RequestHandler): | |
def get(self): | |
self.render("fileuploadform.html") | |
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') | |
fh.write(fileinfo['body']) | |
self.finish(cname + " is uploaded!! Check %s folder" %__UPLOADS__) | |
application = tornado.web.Application([ | |
(r"/", Userform), | |
(r"/upload", Upload), | |
], debug=True) | |
if __name__ == "__main__": | |
application.listen(8888) | |
tornado.ioloop.IOLoop.instance().start() |
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
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
<html> | |
<head> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> | |
<title>Upload Form</title> | |
</head> | |
<body> | |
<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" /> | |
</form> |
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'}
Hi. I’ve got error 405 Method not allowed. Could you please help me, I am a beginner.
Solved. Sorry.