Skip to content

How to: Store the uploaded file size and content type

Henrik Nyh edited this page · 8 revisions
Clone this wiki locally

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


  def update_asset_attributes
    if asset.present? && asset_changed?
      self.content_type = asset.file.content_type
      self.file_size = asset.file.size

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
Something went wrong with that request. Please try again.