【问题标题】:How to get rid of b'' prefix when loading BLOB image to html page?将 BLOB 图像加载到 html 页面时如何去掉 b'' 前缀?
【发布时间】:2019-05-24 08:24:21
【问题描述】:

当我尝试加载用户已提交到数据库的图像数据时,它确实使图像源等于该数据,但它具有前缀 b'',因此它不显示图像。如何删除它以显示图像?

我在将它上传到数据库时尝试从 utf-8 解码它,但它不起作用,因为它被存储为 BLOB,所以会出现二进制错误。我在使用检查元素时手动删除了 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'' 前缀,但它确实有。

【问题讨论】:

    标签: python html sqlalchemy flask-sqlalchemy


    【解决方案1】:

    你需要 decode 到 str 的字节,所以这应该可以工作:

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

    将编码指定为 ASCII 必然适用于 base64 编码的文本,并且如果您的 cod 在默认编码不是 ASCII 的超集(或接近超集)的环境中运行,则可以防止错误。

    【讨论】:

    • 当我将它实现到我的代码中时,它会引发“UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)”的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2016-10-29
    • 1970-01-01
    • 2011-11-15
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多