1. 在数据库中添加图片
缺陷 没有文档过滤功能
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
password_hash = db.Column(db.String(128))
confirmed = db.Column(db.Boolean, default=False)
name = db.Column(db.String(64))
location = db.Column(db.String(64))
about_me = db.Column(db.Text())
member_since = db.Column(db.DateTime(), default=datetime.utcnow)
last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
avatar_hash = db.Column(db.String(32))
以上的avatar_hash 是数据库中的表示。 这个是 用户头像。 但是下面的例子是文章图片
2. 上传图像
首先 表格Form
class PostForm(Form):
avatar = FileField('Change the picture')
name = StringField('What is your posts name?', validators=[Required()])
body = PageDownField("What's on your mind?", validators=[Required()])
submit = SubmitField('Submit')
这是一个上传avatar 图片的表格。
3.视图函数 views
def index():
form = PostForm()
if current_user.can(Permission.WRITE_ARTICLES) and \
form.validate_on_submit():
post = Post(body=form.body.data, name=form.name.data,
author=current_user._get_current_object())
db.session.add(post)
f = request.files['avatar']
fname = secure_filename(f.filename)
if fname != '':
UPLOAD_FOLDER = '\\app\\static\\avatar\\'
f.save(os.getcwd() + UPLOAD_FOLDER + post.name + "_" + fname)
post.avatar_hash = post.name + "_" + fname
return redirect(url_for('.index'))
4.页面
<div class="post-thumbnail">
<a href="{{ url_for('.user', username=post.author.username) }}">
{% if post.avatar_hash != 'None' %}
<img style="width:45px; height:45px"src={{url_for('static',filename='avatar/' + post.avatar_hash)}}> </a>
{%else%}
<img style="width:45px; height:45px"src={{url_for('static',filename='avatar/123.jpg')}}>
{% endif%}
</div>
缺陷 没有文档过滤功能