Flask / Python. Get mimetype from uploaded file
To retrieve the mimetype from an uploaded file using Flask in Python, you can follow these steps:
First, you need to import the necessary modules. In this case, you will need to import the
Flask
module and therequest
module.Create an instance of the Flask application by initializing the
Flask
class. This can be done by callingFlask(__name__)
.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 thePOST
HTTP method.Inside the route function, you can access the uploaded file using the
request
module'sfiles
attribute. For example,file = request.files['file']
will retrieve the uploaded file from the request.To get the mimetype of the uploaded file, you can simply access the
mimetype
attribute of the file object. For example,mimetype = file.mimetype
.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.