我的图像存储在 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
返回它。
有更好的解决方案吗?
最佳答案
使用数据创建响应对象,然后设置内容类型 header 。如果您希望浏览器保存文件而不是显示文件,请将内容处置 header 设置为 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.Headers和 flask.Response
您可以将类似文件的对象和 header 参数传递给 send_file
以让它设置完整的响应。对二进制数据使用 io.BytesIO
:
return send_file(
io.BytesIO(image_binary),
mimetype='image/jpeg',
as_attachment=True,
download_name='%s.jpg' % pid)
在 Flask 2.0 之前,download_name
被称为 attachment_filename
。
关于python - flask 返回存储在数据库中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11017466/