烧瓶返回存储在数据库中的图像 [英] Flask to return image stored in database

查看:58
本文介绍了烧瓶返回存储在数据库中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My images are stored in a MongoDB, and I'd like to return them to the client, here is how the code is like:

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

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

However, it seems that I can't return binary directly in Flask? My idea so far:

  1. 返回图像二进制文件的base64.问题在于IE< 8不支持此功能.
  2. 创建一个临时文件,然后用send_file返回.
  1. Return the base64 of the image binary. The problem is that IE<8 doesn't support this.
  2. Create a temporary file then return it with send_file.

有更好的解决方案吗?

推荐答案

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

Create a response object with the data and then set the content type header. Set the content disposition header to attachment if you want the browser to save the file instead of displaying it.

@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.Headers 您可以将类似文件的对象传递给send_file,并将标头参数传递给send_file,以使其建立完整的响应.将io.BytesIO用于二进制数据:

You can pass a file-like oject to and the header arguments to send_file to let it set up the complete response. Use io.BytesIO for binary data:

return send_file(
    io.BytesIO(image_binary),
    mimetype='image/jpeg',
    as_attachment=True,
    attachment_filename='%s.jpg' % pid)

这篇关于烧瓶返回存储在数据库中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆