5
votes

I am developing Rails 3.2.9 app and using Carrierwave as file uploader. The Carriverwave readme point out the way to get correct content_type:

  1. Add require 'carrierwave/processing/mime_types' to an initializer or your uploader(s).
  2. Add include CarrierWave::MimeTypes to your uploader.
  3. Add process :set_content_type to your uploader(s).

Base on this, My uploader is below:

# encoding: utf-8
require 'carrierwave/processing/mime_types'
class AttachmentUploader < CarrierWave::Uploader::Base
  include CarrierWave::MimeTypes
  storage :file
  def store_dir
    "#{base_store_dir}/#{model.id}"
  end
  process :set_content_type

end

In my model, mount the uploader as file:

mount_uploader :file, AttachmentUploader

However, I always got content_type nil after upload file:

1.9.3-p327 :013 > a.file.class
 => AttachmentUploader
1.9.3-p327 :010 > a.file.file
 => #<CarrierWave::SanitizedFile:0x00000004046330 @file="uploads/course/000/000/026/attachment_file/6/myIcon.png", @original_filename=nil, @content_type=nil> 

Any suggestion? Thanks.

PS: I already added gem "mime-types", "~> 1.19" in my Gemfile.

3

3 Answers

2
votes

You will need to follow the instructions laid out here: https://github.com/carrierwaveuploader/carrierwave#setting-the-content-type

Add the mime-types gem, then setup your uploader file like so

require 'carrierwave/processing/mime_types'

class MyUploader < CarrierWave::Uploader::Base
    include CarrierWave::MimeTypes

    process :set_content_type
 end
2
votes

Had the same problem tried this in my Model file where I mounted the Uploader

before_save :set_mime_type                   

    def set_mime_type
      self.mimetype = Mime::Type.lookup_by_extension(File.extname(self.cf_filename.to_s)[1..-1]) 
    end

Note: You need to have a mimetype field in the table

0
votes

I just hit the exact same problem and couldn't find an easy fix.

My workaround was to add a content_type column to the model and set it in the create/update process with

@model.content_type = params[:file_upload][:attachment].content_type

This works, though hopefully the issue gets fixed.