一般都会存储路径,担忧少数的要求存储图片到数据库。下面的例子介绍了如何在Flask项目里存储图片到数据库以二进制流的方式。并从数据库读取
<span style="font-size:18px;">app\models.py
class Document3(db.Model):
__tablename__ = 'documents3'
id = db.Column(db.Integer, primary_key=True)
resultname = db.Column(db.String(300), index=True)
blob = db.Column(db.LargeBinary(length=2048))
</span>
<span style="font-size:18px;">app\main\forms.py
class upForm(Form):
file = FileField('上传图片:')
name = StringField('真实姓名:')
submit = SubmitField('提交')</span>
<span style="font-size:18px;">app\main\views.py
import base64
@main.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
if current_user.is_authenticated:
user = User.query.filter_by(email=current_user.email).first()
ds = Document3.query.all()
form=upForm()
if form.validate_on_submit():
resultname = form.name.data
files = request.files['file'].read()
resultname=request.files['file'].filename
doc3=Document3(resultname=resultname, blob=files)
db.session.add(doc3)
db.session.commit()
flash('ok')
return render_template('up.html', form=form, ds=ds, base64=base64)
return render_template('up.html')</span>
<span style="font-size:18px;">
<strong>app\template\up.html</strong>
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block main %}
{{ super() }}
<div class="main">
{% include "jindu.html" %}
<div style="width: 85%;margin-left: 2%;">
<form action="" method="post" name="" <strong>enctype="multipart/form-data</strong>">
{{form.hidden_tag()}}
{{ form.name.label }} {{ form.name }}<br><br><br><br>
{{ form.file.label }} {{ form.file }}
{{ form.submit }}
</form>
----------------------------------------------------------------------------------------------------
{% if ds %}
{% for d in ds%}
<p> {{ d.resultname }}------------------------<img src="data:;base64,{{ base64.b64encode(d.blob) }}"/></p>
{% endfor %}
{% endif %}
</div>
</div>
{% endblock %}
</span>