为什么我的Flask应用程序中的图像能够正确显示?

时间:2015-05-13 09:12:23

标签: python upload flask jinja2 image-uploading

我创建了一个User类:

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.')

然后我检查了上传内容' dir并确认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模板中应该采用哪种格式...?或者我错在哪里?请劝告。

1 个答案:

答案 0 :(得分:2)

您能提供一些额外的信息吗?用于呈现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以获取指导。

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