Skip to content
This repository
Browse code

Merge pull request #1248 from hasghari/missing-extension

missing file extension
  • Loading branch information...
commit 11e35cd08edfc0ab6682207820158f0cce385b3f 2 parents 2376746 + e3a46e2
James Miller bensie authored
16 lib/carrierwave/uploader/download.rb
@@ -17,11 +17,12 @@ def initialize(uri)
17 17 end
18 18
19 19 def original_filename
20   - if file.meta.include? 'content-disposition'
21   - match = file.meta['content-disposition'].match(/filename=(\"?)(.+)\1/)
22   - return match[2] unless match.nil?
  20 + filename = filename_from_header || File.basename(file.base_uri.path)
  21 + mime_type = MIME::Types[file.content_type].first
  22 + unless File.extname(filename).present? || mime_type.blank?
  23 + filename = "#{filename}.#{mime_type.extensions.first}"
23 24 end
24   - File.basename(file.base_uri.path)
  25 + filename
25 26 end
26 27
27 28 def respond_to?(*args)
@@ -45,6 +46,13 @@ def file
45 46 raise CarrierWave::DownloadError, "could not download file: #{e.message}"
46 47 end
47 48
  49 + def filename_from_header
  50 + if file.meta.include? 'content-disposition'
  51 + match = file.meta['content-disposition'].match(/filename=(\"?)(.+)\1/)
  52 + return match[2] unless match.nil?
  53 + end
  54 + end
  55 +
48 56 def method_missing(*args, &block)
49 57 file.send(*args, &block)
50 58 end
6 spec/uploader/download_spec.rb
@@ -20,6 +20,7 @@
20 20
21 21 sham_rack_app = ShamRack.at('www.example.com').stub
22 22 sham_rack_app.register_resource('/test.jpg', File.read(file_path('test.jpg')), 'image/jpg')
  23 + sham_rack_app.register_resource('/test-with-no-extension/test', File.read(file_path('test.jpg')), 'image/jpeg')
23 24 sham_rack_app.register_resource('/test%20with%20spaces/test.jpg', File.read(file_path('test.jpg')), 'image/jpg')
24 25 sham_rack_app.handle do |request|
25 26 if request.path_info == '/content-disposition'
@@ -108,6 +109,11 @@
108 109 @uploader.url.should == '/uploads/tmp/1369894322-345-2255/another_test.jpg'
109 110 end
110 111
  112 + it 'should set file extension based on content-type if missing' do
  113 + @uploader.download!('http://www.example.com/test-with-no-extension/test')
  114 + @uploader.url.should == '/uploads/tmp/1369894322-345-2255/test.jpeg'
  115 + end
  116 +
111 117 it 'should not obscure original exception message' do
112 118 expect {
113 119 @uploader.download!('http://www.example.com/missing.jpg')

0 comments on commit 11e35cd

Please sign in to comment.
Something went wrong with that request. Please try again.