Determine file type in Ruby

后端 未结 13 1095
耶瑟儿~
耶瑟儿~ 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:39

    There is a ruby binding to libmagic that does what you need. It is available as a gem named ruby-filemagic:

    gem install ruby-filemagic
    

    Require libmagic-dev.

    The documentation seems a little thin, but this should get you started:

    $ irb 
    irb(main):001:0> require 'filemagic' 
    => true
    irb(main):002:0> fm = FileMagic.new
    => #
    irb(main):003:0> fm.file('foo.zip') 
    => "Zip archive data, at least v2.0 to extract"
    irb(main):004:0> 
    

提交回复
热议问题