Flask to return image stored in database

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.

@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

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:

return send_file(
    io.BytesIO(image_binary),
    mimetype="image/jpeg",
    as_attachment=True,
    attachment_filename="%s.jpg" % pid)

Leave a Comment