http://www.afewords.com/book/502e5cff3725176a91000004/catalog/16
import tornado.ioloop
import tornado.web
UPLOAD_FILE_PATH = '/path/to/files/'
class MainHandler(tornado.web.RequestHandler):
def get(self):
args = dict(username = 'visitor')
self.render('home.html', **args)
class UploadHandler(tornado.web.RequestHandler):
def post(self):
username = self.get_argument('username', 'anonymous')
if self.request.files.get('uploadfile', None):
uploadFile = self.request.files['uploadfile'][0]
filename = uploadFile['filename']
fileObj = open(UPLOAD_FILE_PATH+username+filename, 'wb')
fileObj.write(uploadFile['body'])
self.redirect('/')
application=tornado.web.Application([(r'/',MainHandler),('/upload', UploadHandler) ],
template_path = 'templates',
debug = True
)
if __name__=='__main__':
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload file demo</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="username" value="{{username}}"/>
<input type="file" name="uploadfile" />
<input type="submit" value="upload"/>
</form>
</body>
</html>