My images are stored in a MongoDB, and I’d like to return them to the client, here is how the code is like:
# get image binary from MongoDB, which is bson.Binary type
However, it seems that I can’t return binary directly in Flask? My idea so far:
Return the base64 of the image binary. The problem is that IE<8 doesn't support this. Create a temporary file then return it with send_file. Are there better solutions?
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.
image_binary = read_image(pid)
response = make_response(image_binary)
‘Content-Disposition’, ‘attachment’, filename=’%s.jpg’ % pid)
Relevant: werkzeug.Headers and flask.Response
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:
attachment_filename=’%s.jpg’ % pid)