How to render image from Flask-SQLAlchemy on page?

浪尽此生 提交于 2021-02-07 08:15:39

问题


I'm trying to render image on my website but it's doesn't work (i see only corrupted file icon). Could You please tell me what i'm doing wrong ?

The way how I upload the image:

@app.route('/UploadImages')
def UploadImages():
    return render_template('UploadImages.html')


@app.route('/uploadImages', methods=['POST'])
def uploadImages():
    name = current_user.USERNAME
    file = request.files['inputFile']
    newFile=IMAGES(
        NAME=file.filename,
        USERNAME=name,
        DATA=file.read()
    )
    db.session.add(newFile)
    db.session.commit()

    return 'Saved ' + file.filename + 'to the database !'

Here is my db table:

class IMAGES(db.Model):
    ID = db.Column(db.Integer,primary_key=True)
    NAME = db.Column(db.String(300),unique=True)
    DATA = db.Column(db.BLOB)
    USERNAME = db.Column(db.String(15))

I'm sure that the file is upload correctly because when I use:

@app.route('/download')
def download():
    file_data = IMAGES.query.filter_by(USERNAME='test1').first()

    return send_file(BytesIO(file_data.DATA),
attachment_filename='test.jpg',as_attachment=True) 

I get the image not corrupted.

How I try to render the file:

@app.route('/image')
def image():
    file_data = IMAGES.query.filter_by(USERNAME='test1').first()
    image = b64encode(file_data.DATA)
    return render_template('Image.html',data=list,image=image)

and on the website:

<img src="data:;b64encode,{{ image }}"/>

回答1:


The <img> data URI should be data:;base64,{{ image }} and not data:;b64encode,{{ image }}.




回答2:


As i have read this above the solution given by @Szymo n is the appropriate one for this.

In your main route do these things`

@app.route('/image')
def image():
    file_data = IMAGES.query.filter_by(USERNAME='test1').first()
    image = base64.b64encode(file_data.DATA).decode('ascii')
    return 
render_template('Image.html',data=list,image=image)`

And in html file write the following code:

<img src="data:;base64,{{ image }}"/>


来源:https://stackoverflow.com/questions/44861182/how-to-render-image-from-flask-sqlalchemy-on-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!