【问题标题】:How can I ask user to upload image to an html page, insert this image to an sqlite3 table using flask, and then display this image using jinja?如何要求用户将图像上传到 html 页面,使用烧瓶将此图像插入到 sqlite3 表中,然后使用 jinja 显示此图像?
【发布时间】:2021-03-18 01:15:53
【问题描述】:

到目前为止,这就是我想出的

#html 要求用户输入包括图片在内的信息

    <div class="form-group">
        <input autocomplete="off" autofocus class="form-control" name="name" placeholder="name" type="text">
    </div>
    <div class="form-group">
        <input class="form-control" name="subject" placeholder="subject" type="text">
    </div>
    <div class="form-group">
        <input class="form-control" name="experience" placeholder="experience" type="text">
    </div>
    <div class="form-group">
        <input class="form-control" name="phone" placeholder="puone-number" type="number">
    </div>
    <div class="form-group">
        <input type="file" name="pic" id="pic">
    </div>
    <button class="btn btn-primary" type="submit">Register</button>
</form>

烧瓶

@app.route("/register", methods=["GET", "POST"])
def register():
    """Show teacher registering menu"""
    if request.method == "GET":
        return render_template("register.html")

    else:
        # get the user input
        name = request.form.get("name")
        sub = request.form.get("subject")
        exp = request.form.get("experience")
        phone = request.form.get("phone")
        
        f = request.files['pic']
        pic = f.save(secure_filename(f.filename))
        
        if not name or not sub or not exp or not phone:
            return "404"
        # insert in the database
        sql = "INSERT INTO teachers (name, sub, exp, phone, pic) VALUES (?, ?, ?, ?, ?)"
        db.execute(sql, name, sub, exp, phone, pic)
        # inform the user for the success of the process
        return render_template("success.html")

在 html 上显示结果

<div>
{% for i in query %} 
   
    <div class="media bg-primary text-white">
      <img class="align-self-end mr-3" src={{ i['pic'] }} alt="Generic placeholder image">
      <div class="media-body">
        <h5 class="mt-0">Mr. {{ i['name'] }}</h5>
        <ul class="list-group list-group-flush text-dark">
          <li class="list-group-item">subject: {{ i['sub'] }},</li>
          <li class="list-group-item">experience: {{ i['exp'] }},</li>
          <li class="list-group-item">Contact number: {{ i['phone'] }}</li>
        </ul>
      </div>
    </div>
    <br>
{% endfor %}
</div>

但是现在每次我尝试它时,我都会发现我的 sql 表中 image 列的值为 NULL。 我该如何解决这个问题

【问题讨论】:

    标签: python html sqlite flask jinja2


    【解决方案1】:
    pic = f.save(secure_filename(f.filename))
    

    save 方法返回None,所以这里的pic 将是None

    我认为您打算将其文件名写入数据库,因此也许将其更改为:

    pic = secure_filename(f.filename)
    f.save(pic)
    

    现在pic 是您服务器上的文件名,因此您只需在查看文件的任何位置重建它。

    当然要注意,这使用了用户上传的文件的文件名。您可能希望避免这种情况,以防重复或只是为了清洁。见this other answer我写的关于那个。

    编辑:关于您的模板。

    在模板中加载图片时,假设文件名是image.jpg,并且您使用现有代码:

    <img src={{ i['pic'] }}>
    

    您可以查看渲染页面的源代码,并查看:

    <img src=image.jpg>
    

    这有两个问题:

    • 该属性应该有引号 (&lt;img src="image.jpg"&gt;)
    • 试图从浏览器中呈现的任何路径加载文件,因此如果 URL 是 http://example.com/subdir/,它会在 http://example.com/subdir/image.jpg 处查找图像。这也可以在浏览器开发工具的“网络”标签中进行验证。

    解决办法,用flask的url_for函数构建URL:

    <img src="{{ url_for('static', filename=i['pic']) }}">
    

    当然,这假设您已将文件保存到服务器上的static 目录。您可能希望在 python 代码中确保这一点:

    import os
    # ...
    pic = secure_filename(f.filename)
    f.save(os.path.join('static', pic))
    

    【讨论】:

    • 非常感谢,现在 sql 表显示我能够插入图像。但是我仍然无法从表格中访问图像并将其显示在 html 页面中...请您查看我的第三个代码,这可能是语法问题。
    • 非常感谢您的回复。但是我没有将图像保存在ststic中。该图像假设在我的 sql 表中。这就是我在查询%} 中写 {% for i 的原因。所以它遍历表中的所有行并显示所有结果。现在它显示了除图像之外的所有所需信息。
    • @Ammarios f.save 将图像保存到文件系统,文件名根据代码存储到数据库中。如果您实际上已经实现了其他东西来将数据 blob 保存在数据库中(除了您问题中的代码),那么也许可以查看 this answer 以了解如何将其显示在前端。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2017-12-16
    • 2015-06-02
    • 1970-01-01
    • 2021-01-03
    • 2015-08-05
    相关资源
    最近更新 更多