1

Is there some way to determine the MIME type of a file by it's content without using Magic Library in Python/Django?

I'm getting the content from a HTTP POST and I need to get the mime-type.

I cannot trust the content-type:

request.FILES[request.POST['fileToUpload']].content_type

It can be changed easily by changing the file extension.

document = request.FILES[request.POST['fileToUpload']].read()

I would need to get the content-type of the document:

THX

Aya
  • 39,884
  • 6
  • 55
  • 55
mar mar
  • 1,198
  • 1
  • 7
  • 9
  • 2
    Why don't you want to use a wrapper around [`libmagic`](https://pypi.python.org/pypi/python-magic/)? It is exactly its purpose as far as I can tell... – Sylvain Leroux Jun 12 '13 at 16:06
  • 1
    If you're looking for something built-in to Python, the only similar module is [`imghdr`](http://docs.python.org/2/library/imghdr.html), but that only works for images. If you don't want to use `libmagic` then you'll either have to find an alternative third-party library, or write your own from scratch. – Aya Jun 12 '13 at 16:17
  • 1
    libmagic module uses ctypes and I'm using Jython and I cannot use Ctypes. – mar mar Jun 12 '13 at 16:29
  • 1
    @marmar If you're using Jython, then you can use a Java-based library. See [this question](http://stackoverflow.com/questions/1915317/howto-extract-mimetype-from-a-byte). – Aya Jun 13 '13 at 14:12

2 Answers2

0

You could use the subprocess module to execute /usr/bin/file, if you are on a Unix or Linux system (and possibly on Windows per this question), and have exec privileges. The subprocess module is supported by Jython, and documentation is available at http://www.jython.org/docs/library/subprocess.html.

Brian Minton
  • 3,377
  • 3
  • 35
  • 41
-1

May be not perfect but can do what you need

file_type = request.FILES[request.POST['fileToUpload']].content_type.split('/')[0]
Mounir
  • 11,306
  • 2
  • 27
  • 34