Last Updated: February 25, 2016
·
2.307K
· subosito

Mime Detection on Ruby

require 'ruby-filemagic'
require 'mime/types'

file_path = 'some_document.doc'

# auto detect file's file-type
fm = FileMagic.new(FileMagic::MAGIC_MIME)
mime_type = fm.file(file_path)

puts mime_type
> 'application/msword; content=binary;'

# detect extension by mime_type
file_extension = MIME::Types[mime_type][0].extensions[0]

puts file_extension
> 'doc'