diff --git a/lib/carrierwave/sanitized_file.rb b/lib/carrierwave/sanitized_file.rb index 8043e80eb..7c1676fe3 100644 --- a/lib/carrierwave/sanitized_file.rb +++ b/lib/carrierwave/sanitized_file.rb @@ -331,9 +331,16 @@ def existing_content_type def mime_magic_content_type if path - File.open(path) do |file| - MimeMagic.by_magic(file).try(:type) || 'invalid/invalid' + type = File.open(path) do |file| + MimeMagic.by_magic(file).try(:type) end + + if type.nil? + type = ::MiniMime.lookup_by_filename(path).try(:content_type) + type = 'invalid/invalid' unless type.nil? || type.start_with?('text/') + end + + type end rescue Errno::ENOENT nil diff --git a/spec/fixtures/bork.ABCDE b/spec/fixtures/bork.ABCDE new file mode 100644 index 000000000..e69de29bb diff --git a/spec/sanitized_file_spec.rb b/spec/sanitized_file_spec.rb index 20fb607f5..003b1e5dd 100644 --- a/spec/sanitized_file_spec.rb +++ b/spec/sanitized_file_spec.rb @@ -241,6 +241,26 @@ expect(sanitized_file.content_type).to eq 'invalid/invalid' end + it "returns valid content type on text file" do + file = File.open(file_path('bork.txt')) + + sanitized_file = CarrierWave::SanitizedFile.new(file) + + expect { sanitized_file.content_type }.not_to raise_error + + expect(sanitized_file.content_type).to eq 'text/plain' + end + + it "returns missing content type with unknown extension" do + file = File.open(file_path('bork.ABCDE')) + + sanitized_file = CarrierWave::SanitizedFile.new(file) + + expect { sanitized_file.content_type }.not_to raise_error + + expect(sanitized_file.content_type).to eq "" + end + it "does not raise an error if the path is not present" do sanitized_file = CarrierWave::SanitizedFile.new(nil)