how to python mimetypes.guess_type from a file-like object

后端 未结 3 1145
渐次进展
渐次进展 2021-01-18 12:28
>>> mimetypes.guess_type(\'picture.jpg\')
(\'image/jpeg\', None)

Now I have a file-like object, (eg. stingIO), which content is image\'s d

相关标签:
3条回答
  • 2021-01-18 12:42
    >>> import mimetypes
    >>> print(mimetypes.MimeTypes().guess_type('my_file.txt')[0])
    text/plain
    

    Reference : https://www.tutorialspoint.com/How-to-find-the-mime-type-of-a-file-in-Python

    0 讨论(0)
  • 2021-01-18 12:51

    The python mimetype standard module maps filenames to mime-types and vice versa. To use it, you'll need a filename or a mime-type, in which case it'll give you back a possible file extension.

    It won't/doesn't determine the mime-type based on a file's contents. You need another type of tool to do that. Libmagic, the library behind the unix file command, is one of those tools. The filemagic module (https://pypi.python.org/pypi/filemagic/1.6) is a python interface to libmagic.

    import urllib2
    import magic
    
    img_data = urllib2.urlopen('https://www.google.com/images/srpr/logo11w.png').read()
    # You can add flags 
    # magic.Magic(flags=magic.MAGIC_MIME_TYPE) for take "/image/png"
    m = magic.Magic()
    print m.id_buffer(img_data)
    m.close()
    
    0 讨论(0)
  • 2021-01-18 13:05
    def upload_file():
            if request.method == 'POST':
                f = request.files['file']
                mime_type = f.content_type
    
    0 讨论(0)
提交回复
热议问题