Set the correct content type when using paperclip

Posted on Apr 24, 2011

I have been using paperclip for image uploads for quite some time now.

On a project I am doing right now, I encountered a problem that all of the file uploaded were not in the correct content type. The content type was set as stream and not as the image type that was uploaded.

After some research I found that this problem was occurring because in the file upload process I was using fancy upload (Ajax upload using flash).

The fix was very simple, I just added another post process callback on the model like so:

[ruby]

before_post_process :set_content_type

def set_content_type

self.sketch.instance_write(:content_type, MIME::Types.type_for(self.sketch_file_name).to_s)

end

[/ruby]

Keep in mind you should put this method after the has_attached_file method that paperclip adds or you will get an exception.

Like so:

[ruby]

has_attached_file :avatar,

:styles =>

{

:thumb => “55×55>”,

:preview => “175×175>”,

:huge => “500×500>”

},

:storage => :s3,

:s3_credentials => “#{Rails.root}/config/s3.yml”,

:path => “:class/:attachment/:token/:style.:extension”,

:bucket => ‘your_bucket_name’,

:default_url => “/images/photo01.jpg”

before_post_process :set_content_type

[/ruby]

If you are using Ajax/flash upload, this is the fix for you. The best thing about it is that it’s on the model, using the slim controller fat model best practice and thus it will also happen regardless of the controller you are using to upload the image.