90

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

@app.route("/images/<int:pid>.jpg")
def getImage(pid):
    # get image binary from MongoDB, which is bson.Binary type
    return image_binary

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

  1. 返回base64图像二进制文件的。问题是 IE<8 不支持这个。
  2. 创建一个临时文件,然后用send_file.

有更好的解决方案吗?

4

4 回答 4

156

使用数据创建响应对象,然后设置内容类型标头。attachment如果您希望浏览器保存文件而不是显示文件,请将内容处置标头设置为。

@app.route('/images/<int:pid>.jpg')
def get_image(pid):
    image_binary = read_image(pid)
    response = make_response(image_binary)
    response.headers.set('Content-Type', 'image/jpeg')
    response.headers.set(
        'Content-Disposition', 'attachment', filename='%s.jpg' % pid)
    return response

相关:werkzeug.Headersflask.Response

您可以将类似文件的 oject 和标头参数传递给以send_file使其设置完整的响应。用于io.BytesIO二进制数据:

return send_file(
    io.BytesIO(image_binary),
    mimetype='image/jpeg',
    as_attachment=True,
    attachment_filename='%s.jpg' % pid)
于 2012-06-13T15:05:04.677 回答
48

只是想确认 dav1d 的第二个建议是正确的 - 我测试了这个(其中 obj.logo 是一个 mongoengine ImageField),对我来说很好:

import io

from flask import current_app as app
from flask import send_file

from myproject import Obj

@app.route('/logo.png')
def logo():
    """Serves the logo image."""

    obj = Obj.objects.get(title='Logo')

    return send_file(io.BytesIO(obj.logo.read()),
                     attachment_filename='logo.png',
                     mimetype='image/png')

比手动创建响应对象并设置其标头更容易。

于 2014-08-06T01:10:09.360 回答
13

假设我有存储的图像路径。下面的代码有助于通过发送图像。

from flask import send_file
@app.route('/get_image')
def get_image():
    filename = 'uploads\\123.jpg'
    return send_file(filename, mimetype='image/jpg')

uploads 是我的文件夹名称,其中存在我的 123.jpg 图像。

[PS:上传文件夹应该在你的脚本文件的当前目录中]

希望能帮助到你。

于 2018-10-27T21:49:20.790 回答
6

以下对我有用(对于Python 3.7.3):

import io
import base64
# import flask
from PIL import Image

def get_encoded_img(image_path):
    img = Image.open(image_path, mode='r')
    img_byte_arr = io.BytesIO()
    img.save(img_byte_arr, format='PNG')
    my_encoded_img = base64.encodebytes(img_byte_arr.getvalue()).decode('ascii')
    return my_encoded_img

...
# your api code
...
img_path = 'assets/test.png'
img = get_encoded_img(img_path)
# prepare the response: data
response_data = {"key1": value1, "key2": value2, "image": img}
# return flask.jsonify(response_data )
于 2020-01-13T04:52:45.317 回答