Skip to content

Instantly share code, notes, and snippets.

@Miserlou
Created February 17, 2017 19:07
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
Copy link

kirpit commented Jan 19, 2018

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

@killjoy1221
Copy link

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

@carvendy
Copy link

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

@sarvarside
Copy link

sarvarside commented Mar 29, 2019

@FelixWeichselgartner
Copy link

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

@R1234A
Copy link

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