烧瓶返回存储在数据库中的图像

我的图像存储在MongoDB中,我想将它们返回给客户端,代码如下:


@app.route("/images/<int:pid>.jpg")

def getImage(pid):

    # get image binary from MongoDB, which is bson.Binary type

    return image_binary

但是,我似乎无法直接在Flask中返回二进制文件?到目前为止,我的想法是:


返回base64图像二进制文件的。问题是IE <8不支持此功能。

创建一个临时文件,然后使用返回send_file。

有更好的解决方案吗?


幕布斯6054654
浏览 348回答 3
3回答

九州编程

用数据创建一个响应对象,然后设置内容类型标题。attachment如果希望浏览器保存文件而不显示文件,则将内容处置标题设置为。@app.route('/images/<int:pid>.jpg')def get_image(pid):&nbsp; &nbsp; image_binary = read_image(pid)&nbsp; &nbsp; response = make_response(image_binary)&nbsp; &nbsp; response.headers.set('Content-Type', 'image/jpeg')&nbsp; &nbsp; response.headers.set(&nbsp; &nbsp; &nbsp; &nbsp; 'Content-Disposition', 'attachment', filename='%s.jpg' % pid)&nbsp; &nbsp; return response相关:werkzeug.Headers和flask.Response您可以将类似文件的Oject和header参数传递send_file给它,以设置完整的响应。使用io.BytesIO二进制数据:return send_file(&nbsp; &nbsp; io.BytesIO(image_binary),&nbsp; &nbsp; mimetype='image/jpeg',&nbsp; &nbsp; as_attachment=True,&nbsp; &nbsp; attachment_filename='%s.jpg' % pid)

MM们

假设我已经存储了图像路径。以下代码有助于发送图像。from flask import send_file@app.route('/get_image')def get_image():&nbsp; &nbsp; filename = 'uploads\\123.jpg'&nbsp; &nbsp; return send_file(filename, mimetype='image/jpg')uploads是我的文件夹名称,其中包含123.jpg的图像。[PS:上载文件夹应位于脚本文件的当前目录中]希望能帮助到你。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python