4

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 }}"/>
0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

I use img src="data:;base64,{{ image }}"/> but still the same. I inspected the image object (Chrome F12) link i think the problem is in transformation (BLOB -> image)
I've just used image = base64.b64encode(file_data.DATA).decode('ascii') and it works :)
This worked for me too! Perhaps, you could add it as an answer, making it easier for everyone to read the solution. I will upvote it.
Has there been updates where this solution is outdated? I am able to convert it although the html side does not work for me
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 }}"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.