Determine file type in Ruby

后端 未结 13 1065
耶瑟儿~
耶瑟儿~ 2020-11-30 22:21

How does one reliably determine a file\'s type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) comman

13条回答
  •  無奈伤痛
    2020-11-30 22:51

    For those who came here by the search engine, a modern approach to find the MimeType in pure ruby is to use the mimemagic gem.

    require 'mimemagic'
    
    MimeMagic.by_magic(File.open('tux.jpg')).type # => "image/jpeg" 
    

    If you feel that is safe to use only the file extension, then you can use the mime-types gem:

    MIME::Types.type_for('tux.jpg') => [#]
    

提交回复
热议问题