当我尝试加载用户已提交到数据库的图像数据时,它的确使图像源等于该数据,但其前缀为b'',因此不会显示该图像。如何删除它以便显示图像?
在将其上传到数据库时,我曾尝试从utf-8对其进行解码,但是由于它被存储为BLOB,因此无法正常工作,因此会出现二进制错误。我在使用inspect元素时手动删除了b'',然后显示图像。
@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'])
在页面上显示时:
<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>
我希望它可以显示它,并且图像源没有b''前缀,但是确实可以。
答案 0 :(得分:0)
您需要decode个字节才能到达str,因此应该可以:
<img src="data:image/jpeg;base64,{{ ipost.image.decode('ascii') }}"
将编码指定为ASCII势必适用于base64编码的文本,并且如果您的鳕鱼在默认编码不是ASCII的超集(或接近超集)的环境中运行,则可以防止错误。