Tornado實現表單的提交,檔案的獲取
阿新 • • 發佈:2018-11-16
#注意下面的config的配置檔案 from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado.options import define, parse_config_file, options from tornado.web import Application, RequestHandler class IndexHandler(RequestHandler): def get(self, *args, **kwargs): html='<form method=post action=/login enctype=multipart/form-data>' \ '<input type=text name=name><br><br>' \ '<input type=password name=password><br><br>' \ '<input type=file name=avatar><br><br>' \ '<input type=submit value=提交> ' \ '<input type=reset value=重置>' \ '</form>' self.write(html) def post(self, *args, **kwargs): pass class LoginHandler(RequestHandler): def get(self, *args, **kwargs): pass def post(self, *args, **kwargs): name = self.get_body_argument('name') password = self.get_body_argument('password') print('使用者名稱: ',name,' , 密碼:', password) files = self.request.files #明確知道使用者就上傳了一張圖片時 #用下標的方式將這唯一一張圖片直接取出 avatar = files.get('avatar')[0] filename = avatar.get('filename') body = avatar.get('body') writer = open('upload/%s' % filename,'wb') writer.write(body) writer.close() define('port',default=8888,type=int,multiple=False) parse_config_file('config') app = Application([('/',IndexHandler),('/login',LoginHandler)]) server = HTTPServer(app) server.listen(options.port) IOLoop.current().start()