Skip to content

How to: Store the uploaded file size and content type

Robert Hopman edited this page Jan 23, 2018 · 11 revisions

Are you looking for how to store the width and height? See: How to: Get image dimensions

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:

class PictureUploader < CarrierWave::Uploader::Base

  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