Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask to return image stored in database

My images are stored in a MongoDB, and I'd like to return them to the client, here is how the code is like:

@app.route("/images/<int:pid>.jpg") def getImage(pid):     # get image binary from MongoDB, which is bson.Binary type     return image_binary 

However, it seems that I can't return binary directly in Flask? My idea so far:

  1. Return the base64 of the image binary. The problem is that IE<8 doesn't support this.
  2. Create a temporary file then return it with send_file.

Are there better solutions?

like image 359
wong2 Avatar asked Jun 13 '12 14:06

wong2


People also ask

How do I return an image from Flask to HTML?

To display image on a HTML page with Python Flask, we can pass the image path to the template from the view. Then we call render_template with the template file name, and the user_image argument set to the image path.

Where are Flask project images stored?

When we want to store an image in our web application made from flask, we can store the image in the folder we allocated for flask app, containing the app.py, scripts. The folder i allocated is look, and within look folder, i made a sub folder called static. Inside static folder, store the image.


1 Answers

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) 
like image 124
dav1d Avatar answered Sep 19 '22 10:09

dav1d