简体   繁体   中英

Flask Images SQLAlchemy doesn't return image

I want to make a project in flask where the user just adds a picture to the sqlalchemy and then all of the user's pictures are showing in an other page.

**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)**

But when I run it and add a picture I don't have any error. But when I go to /a I still don't get an error but the image isn't showing. I get Image . What should I do?

Thanks.

If you save your file with save , the pointer moves to the end of the file. For this reason it is necessary before you read the data a second time to save it in the database, to set the pointer back to the beginning.

@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')

Now all the data is read again and stored in the database. The image should appear on the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM