Limit file size?

955 views
Skip to first unread message

Dru

unread,
Feb 20, 2010, 5:37:21 AM2/20/10
to carrierwave
Apologies if this has already been answered somewhere and I've missed
it. I've got carrierwave setup perfectly using mini_magick and
everything is working great. One thing that I'm missing and have yet
to find a solution too, is limiting the size of uploaded files. I'm
only using this for avatars and a few other things and I really don't
want the uploaded files to be much more than 1Mb or so, especially
since I'm generating thumbs and what-not. Is there any kind of config
option I've missed or another recommended solution?

Any help/suggestions are much appreciated, thanks.

jnicklas

unread,
Feb 20, 2010, 12:00:27 PM2/20/10
to carrierwave
validates_size_of should work, at least with ActiveRecord.

/Jonas

Dru

unread,
Feb 21, 2010, 6:28:21 PM2/21/10
to carrierwave
Thanks for the suggestion. I'm using mongomapper as it happens but
I've got it working how I want now though it's not ideal.

I was curious as to whether validates_size_of would work with
activerecord though as it was my understanding that that is just an
alias of validates_length_of which seems to apply more to strings,
ranges etc. It did however work perfectly, (if anyone else sees this
and wonders).

Federico Gonzalez

unread,
Apr 26, 2011, 10:09:02 PM4/26/11
to carri...@googlegroups.com
It didn't work for me. It is only validating that the name of the file is no longer than what I specify in the validates_size_of

How did you manage to make it work?

Chris Bloom

unread,
Jun 6, 2011, 3:19:44 AM6/6/11
to carri...@googlegroups.com
I created a validator for attachment size. It's basically a clone of the default validates_length_of validator from Rails, except it looks for a Carrierwave attachment and validates the size.


Use it like this:

# app/models/brand.rb
require 'file_size_validator'

class Brand < ActiveRecord::Base
  
  mount_uploader :logo, BrandLogoUploader
    
  validates :logo,
    :presence => true,
    :file_size => { 
      :maximum => 0.5.megabytes.to_i
    }
end

Like validates_length_of, it accepts :maximum, :minimum, :in [range], and :is options.

Trevor Turk

unread,
Jun 6, 2011, 8:09:52 AM6/6/11
to carri...@googlegroups.com
Awesome - please add to the wiki!

Chris Bloom

unread,
Jun 6, 2011, 9:32:13 AM6/6/11
to carrierwave
OK, will do :)
Reply all
Reply to author
Forward
0 new messages