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"
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.
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.
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.
In Ruby on Rails you can do:
MIME::Types.type_for("filename.gif").first.content_type # => "image/gif"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With