简体   繁体   English

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

[英]Why can't my images in Flask application be properly displayed?

I created a User class as such: 我这样创建了一个User类:

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

and a user uploads his avatar as following(UPLOAD_DIR is app/static/upload): 并且用户按以下方式上传他的头像(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.')

Then I checked the 'uploads' dir and confirmed the img was there; 然后,我检查了“上载”目录并确认img在那; and I got this in shell: 我在shell中得到了这个:

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

Now I ran the server and found the img can't be displayed somehow. 现在,我运行服务器,发现img无法以某种方式显示。 My template is like this: 我的模板是这样的:

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

So I wonder in which format should img be in Jinja2 templates...? 所以我想知道img在Jinja2模板中应该采用哪种格式...? Or am I wrong else where? 还是我在其他地方错了? Please kindly advise. 请告知。

Can you provide some additional information? 您能否提供一些其他信息? What is the code for the route you use to render the jinja2 template? 您用来渲染jinja2模板的路线的代码是什么?

Also, it looks like you haven't committed the new path to the database --- you should call db.session.commit() after the new avatar path is added to the user object to ensure that the new data is properly saved: 同样,您似乎尚未提交新的数据库路径---在将新的头像路径添加到用户对象之后,应调用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.')

This matters if, say, you're sending a new user object to the jinja2 template. 例如,如果您要将新的用户对象发送到jinja2模板,则这很重要。 While the route might appear to be saved correctly when you're working with a single user object in the interactive shell, it won't be correct when you perform a new User.query in your route and send the query object as context to the template using render_template() . 当您在交互式外壳程序中使用单个用户对象时,似乎可以正确保存路由,但是当您在路由中执行新的User.query并将查询对象作为上下文发送给使用render_template()模板。

Finally, you should be calling the image location with url_for() . 最后,您应该使用url_for()调用图像位置。 Check this other post for guidance. 查看其他帖子以获取指导。

Good luck -- I hope this helps! 祝您好运-希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM