How to return images in flask response?

70

24

As an example, this URL:

http://example.com/get_image?type=1

should return a response with a image/gif MIME type. I have two static .gif images,
and if type is 1, it should return ok.gif, else return error.gif. How to do that in flask?

wong2

Posted 2011-12-26T15:47:34.163

Reputation: 13 667

Question was closed 2018-02-12T14:32:27.307

Answers

119

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

Martin Geisler

Posted 2011-12-26T15:47:34.163

Reputation: 63 408

1any idea how to do that with flask-restful ? – David V. – 2017-08-23T15:32:33.077

@DavidV. I am trying the same thing. I am going to use an alternate for now. Save the response as a png file and somehow create a URL for that . Then embed that URL in my html page. – Arindam Roychowdhury – 2017-09-26T20:05:12.363

how do i send multiple gifs as return here? – Dhana – 2017-12-05T12:14:30.053

2

It is worth nothing that send_file is an insecure method of sending files, which does not do any sanity checks and is not recommended if sanity checks are handled in your code. More information can be found on this answer

– Vaulstein – 2018-04-05T14:28:48.063