views:

52

answers:

1

Hi, I am using Flask micro-framework 0.6 and Python 2.6

I need to get the mimetype from an uploaded file so I can store it.

Here is the relevent Python/Flask code:

@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        mimetype = #FIXME
        if file:
            file.save(os.path.join(UPLOAD_FOLDER, 'File-Name')
            return redirect(url_for('uploaded_file'))
        else:
            return redirect(url_for('upload'))


And here is the code for the webpage:

<form action="upload_file" method=post enctype=multipart/form-data> 
Select file to upload: <input type=file name=file> 
<input type=submit value=Upload> 
</form> 


The code works, but I need to be able to get the mimetype when it uploads. I've had a look at the Flask docs here: http://flask.pocoo.org/docs/api/#incoming-request-data
So I know it does get the mimetype, but I can't work out how to retrieve it - as a text string, e.g. 'txt/plain'.

Any ideas?

Thank you.

+1  A: 

From the docs:

http://werkzeug.pocoo.org/documentation/dev/datastructures.html#werkzeug.FileStorage

@app.route('/upload_file', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files.get('file')
        if file:
            mimetype = file.content_type
            filename = werkzeug.secure_filename(file.filename)
            file.save(os.path.join(UPLOAD_FOLDER, filename)
            return redirect(url_for('uploaded_file'))
        else:
            return redirect(url_for('upload'))
MattH
Thank you so much! I Will remember about the Werkzeug docs next time :)
Jonathan
@Jonathan: You're welcome! It was linked from the doc page you supplied.
MattH
Well that is slightly embarrassing :S lol
Jonathan