Untuk menyajikan file ke klien, Anda dapat menyiapkan tampilan seperti ini:
@app.route('/client/serve/<file_id>/', methods=['GET', 'POST'])
@login_required
def serve_file(file_id):
from mongoengine.connection import get_db
from gridfs import GridFS, NoFile
from bson.objectid import ObjectId
from flask import make_response
db = get_db()
fs = GridFS(db)
try:
f = fs.get(ObjectId(file_id))
except NoFile:
fs = GridFS(db, collection='images') # mongoengine stores images in a separate collection by default
try:
f = fs.get(ObjectId(file_id))
except NoFile:
raise ValueError("File not found!")
response = make_response(f.read())
response.mimetype = 'image/jpeg'
return response