【问题标题】:Why can't my images in Flask application be properly displayed?为什么我的 Flask 应用程序中的图像无法正确显示?
【发布时间】:2015-07-24 11:29:42
【问题描述】:

我这样创建了一个用户类:

class User(UserMixin, db.Model):
        ###
        avatar = db.Column(db.String(64), default='app/static/upload/default.jpeg')

并且用户上传他的头像如下(UPLOAD_DIR是app/static/upload):

###    
img_name = secure_filename(img.filename)
        img_path = os.path.join(current_app.config['UPLOAD_DIR'], \
                                img_name)
        img.save(img_path)
        current_user.avatar = os.path.join(
                current_app.config['UPLOAD_DIR'], 
                form.avatar.data.filename)
        db.session.add(current_user)
        flash('Upload completed.')

然后我检查了“上传”目录并确认 img 在那里;我在 shell 中得到了这个:

>>> z.avatar
u'C:\\Users\Administrator\\Desktop\\weiboLITE\\app/static/uploads\\162421.jpg'

现在我运行服务器,发现无法以某种方式显示 img。我的模板是这样的:

<div class="thumbnail">
    <img src="{{ user.avatar }}" alt="Avatar not found.">
</div>

所以我想知道在 Jinja2 模板中 img 应该采用哪种格式...?还是我在其他地方错了?请多多指教。

【问题讨论】:

    标签: python upload flask jinja2 image-uploading


    【解决方案1】:

    你能提供一些额外的信息吗?你用来渲染 jinja2 模板的路由代码是什么?

    另外,您似乎还没有提交数据库的新路径 --- 您应该在将新头像路径添加到用户对象后调用 db.session.commit() 以确保正确保存新数据:

    current_user.avatar = os.path.join(
                    current_app.config['UPLOAD_DIR'], 
                    form.avatar.data.filename)
            db.session.add(current_user)
            db.session.commit()   # Try adding this line 
            flash('Upload completed.')
    

    这很重要,例如,您要向 jinja2 模板发送一个新的用户对象。虽然当您在交互式 shell 中使用单个用户对象时,路由可能看起来已正确保存,但当您在路由中执行新的 User.query 并将查询对象作为上下文发送到模板使用render_template()

    最后,您应该使用url_for() 调用图像位置。查看其他post 以获得指导。

    祝你好运——我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多