【问题标题】:Flask pass image from sqlite blob to template烧瓶将图像从 sqlite blob 传递到模板
【发布时间】:2020-05-06 21:42:29
【问题描述】:

enter image description here我有一个将图像存储在其中一列中的数据库,它们存储为 BLOB,这就是我保存它的方式:

with open("download.png", 'rb') as file:
    data = file.read()

cursor.execute("INSERT INTO my_table VALUES (?,?,?,?,?,?) ", (value_list))

这就是我检索它的方式:

cursor.execute("SELECT * FROM my_table")
my_list = cursor.fetchall()
DDBB.close()

这就是我通过它的方式:

@app.route('/')
def index():
    posts = get_posts()

    return render_template("index.html", my_list=posts)

这就是我使用它的目的:

{% for item in my_list %}
<div class="col-4 text-center mt-5">
    <div class="card" style="width: 18rem;">
        <img src="data:image/png;base64,{{ item[0] }}" id="imgslot" class="card-img-top">
        <div class="card-body">
            <p class="mb-1">Name: {{ item[2] }}</p>
            <p class="mb-1">Location: {{ item[1] }}</p>
            <p class="mb-2">{{ item[3] }}</p>
            <p class="mb-2">Posted by: {{ item[4] }}</p>
            <a href="#" class="btn btn-dark">Go somewhere</a>
        </div>
    </div>
</div> 
{% endfor %}

该卡正在正确读取所有内容,但图像未加载,使用 chrome 的检查似乎值是错误传递。

谁能帮我更好地理解这一点(我是flask新手,没有html经验)

【问题讨论】:

  • 我认为这可能会回答您的问题:stackoverflow.com/a/61061587/2052575 您可能需要构建一条单独的路线,该路线执行类似SELECT image_blob FROM table WHERE id = ? 的操作,然后提供该图像。

标签: python html database sqlite flask


【解决方案1】:

在这种情况下,显示添加到数据库的信息和在检查元素中获得的路径将有助于更好地理解错误。确保您正确传递路径。试试这个:https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/

您可以将图像保存在静态文件夹中,然后使用

从那里获取它

&lt;img id="imgID" src="{{ url_for('static',filename=image_name) }}"&gt;

【讨论】:

  • 通过元素检查添加图像
  • 试试这个:pynative.com/… ...我知道你在寻找 sqlite 但语法相似
  • 我试图将它保存在一个变量上然后传递它,这样我就不必在每次打开页面时创建 x 数量的图像(这是索引的一部分,但我是动态地将卡片定位到页面中,因此它显示了数据库部分的所有条目)
【解决方案2】:

问题在于读取值的方式:

for y in range(len(my_list)):
        rec_data=my_list[y][0]

        with open('static/img/post/img'+str(y)+'.jpg','wb') as f:
            f.write(rec_data)

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2020-09-26
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多