• Tornado(1) 上传图片并显示


    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,如果上传的照片为空,则会报告错误

      在这里插入图片描述

  • 相关阅读:
    关于Android中的三级缓存
    Android中的自定义控件(二)
    Android中的自定义控件(一)
    安卓四大组件之内容提供者
    实施面试题
    实施相关资料
    短路运算符
    第二章SQL映射文件
    第一章 初始MyBatis
    周测
  • 原文地址:https://www.cnblogs.com/jlxa162hhf/p/14161226.html
Copyright © 2020-2023  润新知