从数据库瓶返回图像创建 [英] flask return image created from database

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

问题描述

我的图片存储在MongoDB中,我想他们返回给客户端,这里是code是怎么样的:

my images are stored in MongoDB, 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

不过,似乎我不能直接在瓶返回二进制?

However, it seems that I can't return binary directly in Flask?

下面是我想出现在:


  1. 返回到图像二进制文件的BASE64。 - > IE&LT; 8不支持此

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

  1. return the base64 of the image binary. -> IE<8 doesn't support this.
  2. create a temp file then return it with send_file.

有没有更好的解决方案?

Is there better solutions ?

推荐答案

设置正确的标题应该做的伎俩:

Setting the correct headers should do the trick:

@app.route("/images/<int:pid>.jpg")
def getImage(pid):
    response = make_response(image_binary)
    response.headers['Content-Type'] = 'image/jpeg'
    response.headers['Content-Disposition'] = 'attachment; filename=img.jpg'
    return response

相关: werkzeug.Headers 并的flask.Response

编辑:我刚看到你可以把一个文件描述符 flask.sendfile ,所以也许:

I've just seen you can pass a file-descriptor to flask.sendfile, so maybe:

return send_file(io.BytesIO(image_binary))

是更好的方法(没有测试过)。

is the better way (haven't tested it).

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

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