Determine file type in Ruby

后端 未结 13 1019
耶瑟儿~
耶瑟儿~ 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') => [#<MIME::Type: image/jpeg>]
    
    0 讨论(0)
  • 2020-11-30 22:54

    I found shelling out to be the most reliable. For compatibility on both Mac OS X and Ubuntu Linux I used:

    file --mime -b myvideo.mp4
    video/mp4; charset=binary

    Ubuntu also prints video codec information if it can which is pretty cool:

    file -b myvideo.mp4
    ISO Media, MPEG v4 system, version 2

    0 讨论(0)
  • 2020-11-30 22:55

    I recently found mimetype-fu.

    It seems to be the easiest reliable solution to get a file's MIME type.

    The only caveat is that on a Windows machine it only uses the file extension, whereas on *Nix based systems it works great.

    0 讨论(0)
  • 2020-11-30 22:59

    If you're on a Unix machine try this:

    mimetype = `file -Ib #{path}`.gsub(/\n/,"")
    

    I'm not aware of any pure Ruby solutions that work as reliably as 'file'.

    Edited to add: depending what OS you are running you may need to use 'i' instead of 'I' to get file to return a mime-type.

    0 讨论(0)
  • 2020-11-30 23:00

    The best I found so far:

    http://bogomips.org/mahoro.git/

    0 讨论(0)
  • 2020-11-30 23:00

    You could give a go with MIME::Types for Ruby.

    This library allows for the identification of a file’s likely MIME content type. The identification of MIME content type is based on a file’s filename extensions.

    0 讨论(0)
提交回复
热议问题