Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flask serving binary data example
import io
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/logo.jpg')
def logo():
"""Serves the logo image."""
with open("logo.jpg", 'rb') as bites:
return send_file(
io.BytesIO(bites.read()),
attachment_filename='logo.jpeg',
mimetype='image/jpg'
)
@kirpit

This comment has been minimized.

Copy link

@kirpit kirpit commented Jan 19, 2018

You could simply give the bites object to send_file() instead of re-wrapping it in io.BytesIO().

@killjoy1221

This comment has been minimized.

Copy link

@killjoy1221 killjoy1221 commented Jul 28, 2018

@kirpit He would have to get rid of the with statement. It closes the stream before it's used.

@carvendy

This comment has been minimized.

Copy link

@carvendy carvendy commented Mar 23, 2019

image
I don't want to download image, Can online show the image?

@sarvarside

This comment has been minimized.

Copy link

@sarvarside sarvarside commented Mar 29, 2019

@FelixWeichselgartner

This comment has been minimized.

Copy link

@FelixWeichselgartner FelixWeichselgartner commented Dec 6, 2019

I had to add as_attachment=True to send_file to get it to work.
But thanks!

@R1234A

This comment has been minimized.

Copy link

@R1234A R1234A commented Oct 10, 2020

Hi!! Thanks for the code!!
I have a similar code in which multiple files are uploaded and then after processing, I have a string name "b64_encoded_string" as output now this has not to be saved anywhere but to return that string to the web app and download there as .pem file. Earlier I was using without flask and saving it via - pickle.dump( b64_encoded_string, open("license.pem", "wb")).

Instead, I don't want to save anything in the web app and push all the string and download it for the user as .pem file in-app.

If anybody can help me with this, it would be a great help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment