won*_*ng2 59 python binary flask
我的图像存储在MongoDB中,我想将它们返回给客户端,代码如下:
@app.route("/images/<int:pid>.jpg")
def getImage(pid):
# get image binary from MongoDB, which is bson.Binary type
return image_binary
Run Code Online (Sandbox Code Playgroud)
但是,似乎我不能直接在Flask中返回二进制文件?我的想法到目前为止:
base64图像二进制文件.问题是IE <8不支持这一点.send_file.有更好的解决方案吗?
dav*_*v1d 102
使用数据创建响应对象,然后设置内容类型标头.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
Run Code Online (Sandbox Code Playgroud)
相关:werkzeug.Headers和flask.Response
您可以将类似文件的对象传递给头参数,send_file以便让它设置完整的响应.使用io.BytesIO二进制数据:
return send_file(
io.BytesIO(image_binary),
mimetype='image/jpeg',
as_attachment=True,
attachment_filename='%s.jpg' % pid)
Run Code Online (Sandbox Code Playgroud)
Jaz*_*aza 40
只是想确认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')
Run Code Online (Sandbox Code Playgroud)
比手动创建Response对象和设置其标题更容易.
以下内容对我有用(对于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 )
Run Code Online (Sandbox Code Playgroud)
小智 5
假设我已经存储了图像路径。以下代码有助于发送图像。
from flask import send_file
@app.route('/get_image')
def get_image():
filename = 'uploads\\123.jpg'
return send_file(filename, mimetype='image/jpg')
Run Code Online (Sandbox Code Playgroud)
uploads是我的文件夹名称,其中包含123.jpg的图像。
[PS:上载文件夹应位于脚本文件的当前目录中]
希望能帮助到你。