05 diciembre 2009

Determine file type with Ruby and libmagic (aka how the hell get the correct content-type from a browser-uploaded file)

At woices, we needed something to determine the file type of a file in Ruby, as content-type provided by browsers is, well, not the best out there :D

We wanted something like the command file -b --mime-type but without executing this command from ruby (starting a process from ruby is expensive for our needs).

So, libmagic to the rescue! This is the lib which the file command is based on. For ruby, there is a binding in the ruby-filemagic gem, but we need to install first libmagic-dev package to let the gem install properly:
$ sudo apt-get install libmagic-dev
$ sudo gem install ruby-filemagic
Now we can determine mime-type like this:


This script will set the value "audio/mpeg" to the content_type variable.

The syntax is strange and ugly, but the param to the open method is a flag (or a ORed set of flags) that affect behaviour of other libmagic functions. As we needed only the mime type, we pass the MAGIC_MIME_TYPE flag (if not, a textual description of the file will be returned by the file function).

The rest of the flags are explained in libmagic manpage:
$ man libmagic
This was tested with Ubuntu 9.10 Karmic Koala.

No hay comentarios: