Python Flask "send_file()" method TypeError

Question:

I’m trying to read an image that the user uploads and then display the image back to them. I want to do this without saving the image file that is uploaded.

I have code like this:

from flask import Flask, redirect, render_template, request, url_for, send_file
from PIL import Image, ImageDraw
from io import BytesIO

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        img = Image.open(request.files['file'].stream)
        byte_io = BytesIO()
        img.save(byte_io, 'PNG')
        byte_io.seek(0)
        return send_file(byte_io, mimetype='image/png')


if __name__ == '__main__':
    app.run(debug=1)

It produces this error:

TypeError: send_file() got an unexpected keyword argument 'mimetype'

I’ve tried replacing mimetype with other valid parameters and it will just give the same error but with the name of the new parameter. So I think the problem is with my bytes_io.

UPDATE:

To clarify, by send_file() I’m referring to the built in flask.send_file() method:

Asked By: David Skarbrevik

||

Answers:

From flask document

The mimetype guessing requires a filename or an attachment_filename to be provided.

  • mimetype – the mimetype of the file if provided. If a file path is given, auto detection happens as fallback, otherwise an error will be raised.

So, you should provide that like this

return send_file(
    io.BytesIO(obj.logo.read()),
    download_name='logo.png',
    mimetype='image/png'
)

This sample code should run normally,

from flask import Flask, request, send_file
app = Flask(__name__)

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


if __name__ == '__main__':
    app.run()

If you’ve still got same error, maybe it’s an environment problem. You can check your package version using pip freeze.

Answered By: hyun
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.