首页 > 解决方案 > 使用flask在html页面上从gridfs渲染图像

问题描述

我想使用烧瓶在我的 html pyge 上从 gridfs 渲染图像。我使用带有一个按钮的gridfs将图像存储在我的mongodb中,并使用Flask-Session将图像的ObjectId存储在服务器端会话中。当我单击另一个按钮时,我通过我的会话获得了之前存储的图像的正确 ObjectId,然后想在我的 html 页面中从 gridfs 呈现此图像,但我不知道该怎么做。

我的app.py文件:

from flask import Flask, render_template, request, redirect, session
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from gridfs import GridFS
from flask_session import Session

DB = 'test-grid'
COLLECT = 'test-session'


client = MongoClient('mongodb://127.0.0.1:27017')
db = client[DB]
fs = GridFS(db)


app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16*1024*1024
app.config['SESSION_TYPE'] = 'mongodb'
app.config['SESSION_MONGODB'] = client
app.config['SESSION_MONGODB_DB'] = DB
app.config['SESSION_MONGODB_COLLECT'] = COLLECT
Session(app)


@app.route("/")
def home():
    return render_template("index.html")


@app.route('/upload', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f_id = fs.put(f, filename=filename)
        session['f_id'] = f_id
        session['filename'] = filename
        return redirect('/')


@app.route('/display', methods=['GET'])
def display_file():
    if request.method == 'GET':
        f = fs.get(session['f_id'])
        image = f.read()
        return render_template("index.html", user_image=image)


if __name__ == "__main__":
    app.run(debug=True)

我的index.html文件:

<html lang='en'>
  <head>
    <meta charset='UTF-8'/>
  </head>
  <body>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <input type="file" onchange="this.form.submit()" name="file" autocomplete="off" required>
    </form>
    <form method="get" action="/display">
        <input type="submit" value="Display">
    </form>
    <img src="{{ user_image }}" alt="Show image here"/>
  </body>
</html>

我的requirements.txt文件:


Flask
Flask-Session
pymongo

但这不起作用,我得到以下输出: 输出

有人可以帮我解决这个问题吗?也许有例子我可以查一下。

标签: pythonmongodbimageflaskgridfs

解决方案


推荐阅读