Tornado(1) 上传图片并显示
-
1,模板文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if img_error %} <font color="red">{{ img_error }}</font> {% end %} <form action="." method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="提交"> </form> </body> </html>
-
使用img_error来显示上传图片时出现的错误提示
-
2,tornado文件后台处理
import tornado import os from tornado.web import RequestHandler class UploadFileHandler(tornado.web.RequestHandler): def get(self): self.render('index.html', img_error=None) def post(self): image = self.request.files.get('image', '') # files里面部分为[{filename: xx, body: 'xx', content_type:'xx'}, {},....]结构组成 # 因为只有一个照片 if image != '': img = image[0] img_name = img.get('filename', '') img_body = img.get('body', ' ') img_type = img.get('content_type', '') # 保存为二进制流 with open('static/images/' + img_name, 'wb') as f: f.write(img_body) self.set_header('Content-Type', img_type) self.write(img_body) else: self.render('index.html', img_error="图片不能为空") def make_app(): return tornado.web.Application( handlers=[ (r'/', UploadFileHandler), ], template_path=os.path.join(os.path.dirname(__file__), 'templates'), static_path=os.path.join(os.path.dirname(__file__), 'static'), debug=True, ) if __name__ == '__main__': app = make_app() app.listen(8888) tornado.ioloop.IOLoop.instance().start()
-
3,正常上传
- 保存到了本地
-
4,如果上传的照片为空,则会报告错误