Detailed explanation of flask upload avatar example

零下一度
Release: 2017-07-03 09:40:30
Original
1819 people have browsed it

Uploading avatars, I thought for a long time, it was just about uploading files. In fact, there is a path, the database stores this path, and then displays it to the front end, without saying anything, let’s see how it is implemented.

The database settings are as follows

user_image=db.Column(db.String(252),nullable=True)
Copy after login

form form design:

avatar=FileField('头像')
Copy after login

Backend implementation code

 avatar=request.files['avatar']
 fanme=avatar.filename
 upfile=os.getcwd()+('/app/static/avatar/')
 ALLOWER_EXIT=['pang','jpg','jpeg','jig']
flag='.' in fanme and fanme.split('.')[1] in ALLOWER_EXITif not flag:     return render_template('editperson.html',form=form)
 avatar.save('{}{}{}'.format(upfile,user.username,fanme))
 user.user_image='/static/avatar/{}{}'.format(user.username,fanme)
 db.session.add(user)
Copy after login

The storage path is

/static/avatar/,支持格式 pang、jpg、jpeg等格式,这个可以根据自己的需求进行设置。 
存储后会在数据库存储一个路径
最后实现后数据库
Copy after login

The next is the front-end display

{% if username.user_image%}<img   src="{{username.user_image}}" style="height:80px;">{%else%}<img src="/static/img/0.jpg" style="height:70px;width:80px">{%endif%}
Copy after login

Let me explain here, the code for uploading avatars in the backend here reports an error on Windows, saying that the file does not exist. I tried to modify it, but the path name should not be too long,

The path name can be short, but an error will be reported if it is long. Windows development has many drawbacks, but there is no problem in implementing it on Ubuntu

项目地址
Copy after login

The above is the detailed content of Detailed explanation of flask upload avatar example. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template