Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

carrierwave content_type always nil

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.

like image 522
jasli2 Avatar asked Oct 05 '22 16:10

jasli2


2 Answers

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
like image 120
Joe Avatar answered Oct 10 '22 03:10

Joe


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

like image 37
Karan Purohit Avatar answered Oct 10 '22 01:10

Karan Purohit