Development Tip

Ruby에서 파일 유형 결정

yourdevel 2020. 11. 1. 18:46
반응형

Ruby에서 파일 유형 결정


한 사람이 어떻게 않는 안정적으로 파일의 유형을 결정? 파일 확장자 분석은 허용되지 않습니다. UNIX file (1) 명령과 유사한 rubyesque 도구가 있어야합니까?

이는 디렉토리, 파일 또는 소켓과 같은 파일 시스템 분류가 아니라 MIME 또는 콘텐츠 유형에 관한 것입니다.


libmagic필요한 작업을 수행 하는 루비 바인딩 이 있습니다. ruby-filemagic 이라는 gem으로 사용할 수 있습니다 .

gem install ruby-filemagic

필요 libmagic-dev합니다.

문서는 약간 얇아 보이지만 시작하면됩니다.

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

Unix 시스템을 사용하는 경우 다음을 시도하십시오.

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

나는 '파일'만큼 안정적으로 작동하는 순수한 Ruby 솔루션을 알지 못합니다.

추가 편집 : 실행중인 OS에 따라 MIME 유형을 반환 할 파일을 가져 오기 위해 'I'대신 'i'를 사용해야 할 수 있습니다.


나는 포격이 가장 신뢰할 만하다는 것을 알았습니다. Mac OS X 및 Ubuntu Linux에서 호환성을 위해 다음을 사용했습니다.

file --mime -b myvideo.mp4
비디오 / mp4; charset = binary

우분투는 가능한 경우 비디오 코덱 정보도 인쇄합니다.

file -b myvideo.mp4
ISO 미디어, MPEG v4 시스템, 버전 2


파일의 매직 헤더에이 신뢰할 수있는 메서드 기반을 사용할 수 있습니다.

def get_image_extension(local_file_path)
  png = Regexp.new("\x89PNG".force_encoding("binary"))
  jpg = Regexp.new("\xff\xd8\xff\xe0\x00\x10JFIF".force_encoding("binary"))
  jpg2 = Regexp.new("\xff\xd8\xff\xe1(.*){2}Exif".force_encoding("binary"))
  case IO.read(local_file_path, 10)
  when /^GIF8/
    'gif'
  when /^#{png}/
    'png'
  when /^#{jpg}/
    'jpg'
  when /^#{jpg2}/
    'jpg'
  else
    mime_type = `file #{local_file_path} --mime-type`.gsub("\n", '') # Works on linux and mac
    raise UnprocessableEntity, "unknown file type" if !mime_type
    mime_type.split(':')[1].split('/')[1].gsub('x-', '').gsub(/jpeg/, 'jpg').gsub(/text/, 'txt').gsub(/x-/, '')
  end  
end

File 클래스를 사용하는 경우 @PatrickRichie의 답변에 따라 다음 함수로 확장 할 수 있습니다.

class File
    def mime_type
        `file --brief --mime-type #{self.path}`.strip
    end

    def charset
        `file --brief --mime #{self.path}`.split(';').second.split('=').second.strip
    end
end

그리고 Ruby on Rails를 사용하는 경우이를 config / initializers / file.rb에 드롭하고 프로젝트 전체에서 사용할 수 있습니다.


You could give shared-mime a try (gem install shared-mime-info). Requires the use ofthe Freedesktop shared-mime-info library, but does both filename/extension checks as well as "magic" checks... tried giving it a whirl myself just now but I don't have the freedesktop shared-mime-info database installed and have to do "real work," unfortunately, but it might be what you're looking for.


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>]

Pure Ruby solution using magic bytes and returning a symbol for the matching type:

https://github.com/SixArm/sixarm_ruby_magic_number_type

I wrote it, so if you have suggestions, let me know.


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.


The best I found so far:

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


This was added as a comment on this answer but should really be its own answer:

path = # path to your file

IO.popen(
  ["file", "--brief", "--mime-type", path],
  in: :close, err: :close
) { |io| io.read.chomp }

I can confirm that it worked for me.


The ruby gem is well. mime-types for ruby


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.

참고URL : https://stackoverflow.com/questions/51572/determine-file-type-in-ruby

반응형