Flask / Python. Get mimetype from uploaded file

To retrieve the mimetype from an uploaded file using Flask in Python, you can follow these steps:

  1. First, you need to import the necessary modules. In this case, you will need to import the Flask module and the request module.

  2. Create an instance of the Flask application by initializing the Flask class. This can be done by calling Flask(__name__).

  3. Define a route for file upload. This can be done by using the @app.route() decorator and specifying the URL path as an argument. For example, @app.route('/upload', methods=['POST']) will create a route for the /upload URL path with the POST HTTP method.

  4. Inside the route function, you can access the uploaded file using the request module's files attribute. For example, file = request.files['file'] will retrieve the uploaded file from the request.

  5. To get the mimetype of the uploaded file, you can simply access the mimetype attribute of the file object. For example, mimetype = file.mimetype.

  6. You can then return the mimetype as a response or perform any further processing as needed.

Here is an example of how the code might look:

from flask import Flask, request

app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload_file():
    file = request.files['file']
    mimetype = file.mimetype
    return mimetype

Hope this helps! Let me know if you have any further questions.