Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect MIME type of uploaded file in Ruby

Is there a bullet proof way to detect MIME type of uploaded file in Ruby or Ruby on Rails? I'm uploading JPEGs and PNGs using SWFupload and content_type is always "application/octet-stream"

like image 594
Vincent Avatar asked Jan 05 '11 03:01

Vincent


People also ask

What is MIME type detection?

MIME detection This uses the GNU file utility to determine the type of the file, which should work right away under Linux. Note that the file utility provided by other Unixes may not support the -i option, and will thus not work. The GNU file utility is also available for Mac OS-X, and for Windows via Cygwin.

Do all files have a MIME type?

There are too many issues with MIME types on different operating systems, different applications saving files differently, some files not having a MIME at all, and lastly, the fact that the extension and MIME could be altered by a malicious user or program.


2 Answers

The ruby-filemagic gem will do it:

require 'filemagic'  puts FileMagic.new(FileMagic::MAGIC_MIME).file(__FILE__) # => text/x-ruby; charset=us-ascii 

This gem does not look at the file extension at all. It reads a bit of the file contents and uses that to guess the file's type.

like image 153
Wayne Conrad Avatar answered Sep 20 '22 19:09

Wayne Conrad


In Ruby on Rails you can do:

MIME::Types.type_for("filename.gif").first.content_type # => "image/gif" 
like image 41
NARKOZ Avatar answered Sep 22 '22 19:09

NARKOZ