【发布时间】:2018-05-25 14:45:28
【问题描述】:
大家好,我是 Python 新手。 所以我有一个困惑的问题。我需要将图像存储在数据库中,然后我必须在客户端显示每个图像。我正在使用 Flask 进行休息请求。
所以这里我有提交的简单标记
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="image">Select image</label>
<input type="file" name='img' id='image'>
<input type="submit" id='upload_img'>
</form>
我在这里收到我的请求并将其保存到我的数据库中
@app.route("/upload", methods=["POST"])
def upload_image():
# get current image file
img_file = request.files['img']
# get Content Type and File Name of current image
content_type = img_file.content_type
filename = img_file.filename
# save to GridFS my image
# fields <-- recive the id of just saved image
fields = db.FS.put(img_file, content_type=content_type, filename=filename)
# store the filename and _id to another database
# so here we can much morea easaly get image from our GridFS
db.Mongo['images'].insert({"filename": filename, "fields": fields})
return index(images=[])
我的简单数据库模型
class db(object):
URI = "mongodb://localhost:27017"
Mongo = None
FS = None
@staticmethod
def initialize():
client = pymongo.MongoClient(db.URI)
db.Mongo= client['gallery']
db.FS = GridFS(Database.DATABASE)
并且所有的保存都成功了。
从数据库中检索我的图像并尝试将其发送到客户端
@app.route('/get_all_images')
def get_image():
images = db.Mongo['gallery'].find({})
# try to get just a first image _id and fing it at GridFS files
image = db.FS.get(images[0]["fields"])
#send to the client
return index(images=image.read())
这是响应中显示图像的标记
<div>
<img src="data:image/png;base64,{{images}}" alt="">
<div>{{images}}</div>
</div>
最后我得到了这样的东西enter image description here
响应如下所示: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00w\x00\x00\x00\x7f\x08\x06\x00\x00\x00\xd5j] \xe7\x00\x00\x00\x19tEXtSoftware\x00Adobe ImageReadyq\xc9e
问题是我无法弄清楚如何将此字节格式转换为真实图像..并直接从数据库将其显示在网页上。
我尝试制作几种变体来解决这个问题..但在某些方面我的想法是如何爆炸的..我真的不明白如何使用它。
感谢您的宝贵时间 :)
如果有人有任何 idias 或建议我如何将图像从数据库显示到客户端...
【问题讨论】:
-
我相信这个问题很常见......但我一开始就坚持这个案例