How do I find mime-type in Python [duplicate]
I am trying out some CGI-scripting in Python. If a request come to my python script, how do I find the mime-type of the filetype?
UPDATE: Adding more info Some images for now, adderess/image.jpg. But if I understand mime-type is part of the headers that the web-browsers sends, right? So how do I read these headers?
You have two options. If your lucky the client can determine the mimetype of the file and it can be included in the form post. Usually this is with the value of the an input element whose name is "filetype" or something similar.
Otherwise you can guess the mimetype from the file extension on the server. This is somewhat dependent on how up-to-date the mimetypes module is. Note that you can add types or override types in the module. Then you use the "guess_type" function that interprets the mimetype from the filename's extension.
import mimetypes
mimetypes.add_type('video/webm','.webm')
...
mimetypes.guess_type(filename)
UPDATE: If I remember correctly you can get the client's interpretation of the mimetype from the "Content-Type" header. A lot of the time this turns out to be 'application/octet-stream' which is almost useless.
So assuming your using the cgi module, and you're uploading files with the usual multipart form, the browser is going to guess the mimetype for you. It seems to do a decent job of it, and it gets passed through to the form.type parameter. So you can do something like this:
import cgi
form = cgi.FieldStorage()
files_types = {};
if form.type == 'multipart/form-data':
for part in form.keys():
files_types[form[part].filename] = form[part].type
else:
files_types[form.filename] = form.type
Assuming you are submitting files with an HTML form like this:
<form enctype="multipart/form-data" method="post">
<input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
You can get the file type with this in a Python CGI script:
form = cgi.FieldStorage()
filetype = form['userfile'].type
Take into account that the submitted file type is determined by the client web browser. It is not detected by Python CGI library or the HTTP server. You may use Python mimetypes module to guess MIME types from file extensions (e.g.: mimetypes.guess_type(form['userfile'].name)
). You could also use the UNIX file
command for the highest reliability although this is usually too costly.
You can install the package with pip install filemime
and use it as follows. all type of files find file type and mime type filemime
from filemime import filemime
fileObj = filemime()
mime = fileObj.load_file("Kodi_Kodi.mp3",mimeType=True)
print(f"mime-type: {mime}")
output:
mime-type: 'audio/mpeg'
精彩评论