Home > Article > Backend Development > Detailed explanation of flask upload avatar example
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)
form form design:
avatar=FileField('头像')
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)
The storage path is
/static/avatar/,支持格式 pang、jpg、jpeg等格式,这个可以根据自己的需求进行设置。 存储后会在数据库存储一个路径 最后实现后数据库
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%}
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
项目地址
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!