烧瓶图像 SQLAlchemy 不返回图像



我想在flask中创建一个项目,用户只需向sqlalchemy添加一张图片,然后所有用户的图片都显示在另一个页面中。

**from flask import Flask,render_template,request,Response
from flask_sqlalchemy import SQLAlchemy
from base64 import b64encode
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users1.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Images(db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.Text)
img =  db.Column(db.LargeBinary)
db.create_all()
mylist = []
@app.route('/',methods=['POST','GET'])
def home():
if request.method == 'POST':
img1 = request.files['ab']
imager = img1.save(secure_filename(img1.filename))
imager = Images(name='abc',img=img1.read())
db.session.add(imager)
db.session.commit()
return render_template('other.html')
@app.route('/a',methods=['POST','GET'])
def home1():
images = Images.query.filter_by(name='abc').all()
for image in images:
image.uri_src = b64encode(image.img).decode('utf-8')
return render_template('new.html',posts=images)
if __name__ == '__main__':
app.run(debug=True)**

但是当我运行它并添加图片时,我没有任何错误。但是当我转到/a时,我仍然没有得到错误,但是图像没有显示出来。我得到的形象。我该怎么办?

谢谢。

如果使用save保存文件,则指针移动到文件的末尾。因此,有必要在第二次读取数据之前将其保存在数据库中,将指针设置回开始位置。

@app.route('/',methods=['POST','GET'])
def home():
if request.method == 'POST':
img1 = request.files['ab']
imager = img1.save(secure_filename(img1.filename))
img1.seek(0) 
imager = Images(name='abc',img=img1.read())
db.session.add(imager)
db.session.commit()
return render_template('other.html')

现在再次读取所有数据并将其存储在数据库中。图片应该出现在页面上。

最新更新