Detect MIME type of uploaded file in Ruby

后端 未结 7 1009
刺人心
刺人心 2020-12-02 09:45

Is there a bullet proof way to detect MIME type of uploaded file in Ruby or Ruby on Rails? I\'m uploading JPEGs and PNGs using SWFupload and content_type is alw

7条回答
  •  被撕碎了的回忆
    2020-12-02 10:22

    You can use this reliable method base on the magic header of the file :

    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
    

提交回复
热议问题