Search code examples
ruby-on-railsrubyfile-uploadswfupload

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"


Solution

  • 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.