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

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

问题描述

我的图像存储在 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中返回binary?到目前为止我的想法:

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.Headersflask.Response

您可以将类似文件的对象传递给 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)

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

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