0

When I try to load image data that the user has submitted to then database, it does make the image source equal to that data but it has the prefix b'' so it does not display the image. How do I remove it so the image will display?

I have tried decoding it from utf-8 when uploading it to the database but it doesn't work as it is being stored as a BLOB so you get binary errors. I have manually removed the b'' when using inspect element and then it displays the image.

@app.route('/imagePost', methods=['POST'])
def imagePost():

    POST_IMAGE_TITLE = str(request.form['imageTitle'])
    POST_IMAGE_DESC = str(request.form['imageDescription'])
    image = request.files['file']
    image = b64encode(image.read())


    Session = sessionmaker(bind=engine)
    s = Session()

    userID = session['userID']
    Username = session['logged_user']

    currentDT = datetime.datetime.now()
    currentDT = currentDT.strftime("%Y-%m-%d %H:%M:%S")

    #make text post
    imagePost = Image(POST_IMAGE_TITLE, POST_IMAGE_DESC, image, userID,Username,currentDT)
    s.add(imagePost)
    s.commit()

    return home()
from flask import Flask
from sqlalchemy.orm import sessionmaker
from flask import Flask, flash, redirect, render_template, request, session, abort
from base64 import b64encode
import base64
import os

import datetime
# this will allow us to access the orm objects
from setDB import *

# creates database engine to database location
engine = create_engine('sqlite:///myDatabase.db', echo=True)

# creates an instance of Flask 
app = Flask(__name__)

# route decorator for the default path
@app.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        users = []
        posts = []
        iPosts = []
        Session = sessionmaker(bind=engine)
        s = Session()
        posts = s.query(Text).order_by(desc(Text.time)).all() # https://stackoverflow.com/questions/4186062/sqlalchemy-order-by-descending
        iPosts = s.query(Image).order_by(desc(Image.time)).all()
        if request.form:
            try:
                users = s.query(User)
            except Exception as e:
                print("Failed to fetch users")
                print(e)
        return render_template("welcome.html", users=users, posts=posts, iPosts=iPosts, userID=session['userID'])

when displaying it on the page:

<div class="col-sm-4">
                {% for ipost in iPosts %}
                <h3 class="mt-5">{{ ipost.imageTitle }}</h3>
                <p3 class="lead">{{ipost.imageDescription}}</p3>
                <img src="data:image/jpeg;base64,{{ ipost.image }}" alt="image for post"> <!---get rid of b' prefix -->
                <br></br>
                <small>{{ipost.Username}}</small>
                <small>{{ipost.time}}</small>
                <br><hr size=1></br>
                {% endfor %}
            </div>

I expect it to display it and the image source not to have the b'' prefix but it does.

1 Answers1

0

You need to decode the bytes to str, so this ought to work:

<img src="data:image/jpeg;base64,{{ ipost.image.decode('ascii') }}"

Specifying the encoding as ASCII is bound to work for base64-encoded text, and prevent errors if your cod is running in an environment where the default encoding is not a superset (or near superset) of ASCII.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • It throws an error of "UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)" when I implement it into my code – CyanDeathReaper Jun 03 '19 at 13:24