Detecting MIME type of data

I’m uploading files via file_column, any suggestions on how to detect
the MIME type of a file? I’d rather not do it by a custom file
extension parser. It looks like ruby has MIME/Type, but it doesn’t seem
to read files.

i think this should be what you want:

:blabla is assumed to be the name of the form file field.

params[:blabla].content_type

if the file is being uploaded as part of a form, then you can use the
content_type method. If you’re reading the file from disk, you can
use the Mime::Types gem from http://mime-types.rubyforge.org/, in
which case you’d do something like:

content_type =
MIME::Types.type_for(‘filename_with_extension’).first.content_type

Mike

What if you don’t have a filename with extension or the extension is
unreliable? Is there any lib out there that can accurately detect type
(mime type) by looking at the data itself?

Thanks for the help.

Bruno C. wrote:

Apparently, no lib can provide the auto detection type. If you’re
using linux, use the command ‘file’:

file -bi my_file.strip

Belatedly…

http://shared-mime.rubyforge.org/ looks interesting, has some support
for identifying mime-type by ‘magic numbers’

Apparently, no lib can provide the auto detection type. If you’re
using linux, use the command ‘file’:

file -bi my_file.strip