diff --git a/carrierwave.gemspec b/carrierwave.gemspec index 62e5e5d57..84362f3fb 100644 --- a/carrierwave.gemspec +++ b/carrierwave.gemspec @@ -28,6 +28,8 @@ Gem::Specification.new do |s| s.add_dependency "activemodel", ">= 3.2.0" s.add_dependency "json", ">= 1.7" s.add_dependency "mime-types", ">= 1.16" + s.add_dependency "mimemagic", ">= 0.3.0" + if RUBY_ENGINE == 'jruby' s.add_development_dependency 'activerecord-jdbcpostgresql-adapter' else diff --git a/lib/carrierwave/sanitized_file.rb b/lib/carrierwave/sanitized_file.rb index 0d6d93ad9..5e645270b 100644 --- a/lib/carrierwave/sanitized_file.rb +++ b/lib/carrierwave/sanitized_file.rb @@ -2,6 +2,7 @@ require 'pathname' require 'active_support/core_ext/string/multibyte' +require 'mimemagic' begin # Use mime/types/columnar if available, for reduced memory usage @@ -253,12 +254,10 @@ def to_file # [String] the content type of the file # def content_type - return @content_type if @content_type - if @file.respond_to?(:content_type) and @file.content_type - @content_type = @file.content_type.to_s.chomp - elsif path - @content_type = ::MIME::Types.type_for(path).first.to_s - end + @content_type ||= + existing_content_type || + mime_magic_content_type || + mime_types_content_type end ## @@ -318,6 +317,22 @@ def sanitize(name) return name.mb_chars.to_s end + def existing_content_type + if @file.respond_to?(:content_type) && @file.content_type + @file.content_type.to_s.chomp + end + end + + def mime_magic_content_type + MimeMagic.by_magic(File.open(path)).try(:type) if path + rescue Errno::ENOENT + nil + end + + def mime_types_content_type + ::MIME::Types.type_for(path).first.to_s if path + end + def split_extension(filename) # regular expressions to try for identifying extensions extension_matchers = [