diff --git a/lib/carrierwave/sanitized_file.rb b/lib/carrierwave/sanitized_file.rb index fd5d3a378..734c00d54 100644 --- a/lib/carrierwave/sanitized_file.rb +++ b/lib/carrierwave/sanitized_file.rb @@ -330,9 +330,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 70298776d..306830c38 100644 --- a/spec/sanitized_file_spec.rb +++ b/spec/sanitized_file_spec.rb @@ -221,6 +221,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)