美文网首页
用户图片上传和保存功能的完整实现(十六)

用户图片上传和保存功能的完整实现(十六)

作者: 梦捷者 | 来源:发表于2020-04-15 08:58 被阅读0次

    一、功能实现步骤如下所示:

    1、编写相关出处理get/post方法的图片上传类(在main.py模块中进行)

    class UploadHandler(BaseHandler):
        """
        用户上传图片信息
        """
        @tornado.web.authenticated
        def get(self):
            self.render('user/upload.html', username=self.current_user)
    
        @tornado.web.authenticated
        def post(self):
            try:
                files = self.request.files['picture']#list类型中包含一个字典
                if files[0]:
                    dict_img = files[0]
                    filename = dict_img['filename']
                    print(filename)
                    print(dict_img['content_type'])
                    save_path = 'static/upload/{}'.format(filename)
                    with open(save_path, 'wb') as f:
                        f.write(dict_img['body'])
                    im = Image.open(save_path)
                    im.thumbnail((200, 200))
                    im.save('static/thumbs/thumb_{}'.format(filename), 'JPEG')
                    post_id = add_post(self.current_user, 'upload/{}'.format(filename), 'thumbs/thumb_{}'.format(filename))
                    print(post_id)
                    if post_id:
                        self.redirect('/post/{}'.format(str(post_id)))
                else:
                    self.write("上传失败,系统不听话")
            except Exception as e:
                print(e)
                self.redirect('/upload')
    

    2、增加add_post方法来进行图片信息的添加操作

    def add_post(username, image_url, thumb_url):
        session = Session()
        user = session.query(User).filter_by(username=username).first()
        post = Post(user_id=user.id, image_url=image_url, thumb_url=thumb_url)
        session.add(post)
        session.commit()
        post_id = post.user_id
        session.close()
        return post_id
    

    3、再进行添加路由

    handlers=[(r'/upload',main.UploadHandler)]
    

    4、编写前端代码

    <!DOCTYPE html>
    <html lang="zh-CN" >
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../static/upload/hu.ico">
        <title>上传图片界面</title>
        <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <link href="../../static/css/signin.css" rel="stylesheet">
      </head>
      <body background="../../static/upload/2.jpg">
      <nav class="navbar navbar-inverse navbar-fixed-top">
          <div class="container-fluid">
            <div class="navbar-header">
                   {% if username!= None %}
              <a class="navbar-brand" href="#">当前在线用户:<font style="color: yellow;font-size:20px">{{ username }}</font></a>
                 {% end %}
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav navbar-right">
                   <li style="margin-right:40px "><a href="/logout"><font style="color: yellow;font-size:20px">退出</font></a></li>
    
              </ul>
            </div>
          </div>
        </nav>
    
    
        <div class="container"  style="margin-top: 80px">
    
          <form class="form-signin" action="/upload" enctype="multipart/form-data" method="post">
            <h2 class="form-signin-heading" style="margin-left: 37px;color: yellow">请上传相应的文件</h2>
               <label for="inputfile" class="sr-only">用户名</label>
            <input type="file" id="inputfile" class="form-control"  required autofocus name="picture">
            <button class="btn btn-lg btn-primary btn-block" type="submit">上传</button>
          </form>
    <div  style="margin-left: 547px">
               <font size="3"> <b>查看上传图片,<a href="/check">直接点我</a></b></font>
            </div>
        </div>
      </body>
    </html>
    

    相关文章

      网友评论

          本文标题:用户图片上传和保存功能的完整实现(十六)

          本文链接:https://www.haomeiwen.com/subject/eakupctx.html