Skip to content

How to: Store the uploaded file size and content type

Bernd Jünger edited this page Oct 29, 2013 · 6 revisions

Simply add the relevant attributes to your model and introduce a before_save callback. In the example below, assume we have an assets table and a mounted AssetUploader.

class Asset < ActiveRecord::Base
  mount_uploader :asset, AssetUploader

  before_save :update_asset_attributes
  
  private
  
  def update_asset_attributes
    if asset.present? && asset_changed?
      self.content_type = asset.file.content_type
      self.file_size = asset.file.size
    end
  end
end

Another way.

Add your attributes into your model.(file_size and content_type).

In your Uploader add this:

require 'carrierwave/processing/mime_types'

class PictureUploader < CarrierWave::Uploader::Base
 include CarrierWave::MimeTypes
  
  process :set_content_type
  process :save_content_type_and_size_in_model

  def save_content_type_and_size_in_model
    model.content_type = file.content_type if file.content_type
    model.file_size = file.size
  end
end
Clone this wiki locally