18

In our latest application we need to process some uploads, I've worked with paperclip before and everything just works! but we're giving carrierwave a try, it looks promising but, I can't find how to validate the size of an attachment, it seems like the documentation doesn't have any information about it, should we add it manually to the model via a custom validator?

Thanks in advance!

Matt Briggs
  • 41,224
  • 16
  • 95
  • 126
jpemberthy
  • 7,473
  • 8
  • 44
  • 52
  • 3
    It seems like they don't have it (yet) Just added this custom validator to my model, => https://gist.github.com/795665 – jpemberthy Jan 25 '11 at 21:08
  • i was working with the above solution a bit myself. just be aware that that will only validate the size of the image after it has been stored in the cache. in terms of client side validation i still am looking myself – Will Ayd Mar 08 '11 at 03:07
  • If you want to secure your site from uploading ridiculously large files, CarrierWave validations won't help, instead learn [how to secure server](http://stackoverflow.com/questions/2200188/rails-file-upload-size-limit). CarrierWave file size validations could be useful if you want to have different size limits for videos and images or you want to validate minimum file size. – skalee Jun 03 '12 at 11:18

4 Answers4

21

There is a Wiki entry on github: https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Validate-attachment-file-size

Flov
  • 1,527
  • 16
  • 25
5

I've made an Active Model File Validators gem that checks content type and file size validation for Carrierwave, PaperClip, Drangonfly, Refile (hopefully it will work with other uploading solutions). It detects the content type based on the content of the file and it has a media type spoof detector. It works both before and after uploads.

Musaffa
  • 702
  • 8
  • 14
5

Since 1.0 version CarrierWave has built-in file size validation.

Install latest carrierwave gem

gem 'carrierwave', '~> 1.0'

Add method size_range to provide a min size and a max size

class ImageUploader < CarrierWave::Uploader::Base
  def size_range
    0..2.megabytes
  end

In model add validates_integrity_of to valid a file size (and content type) of an image.

class Image < ApplicationRecord
  mount_uploader :image, ImageUploader

  validates_integrity_of :image
Alex Kojin
  • 5,044
  • 2
  • 29
  • 31
-1

Here is the solution that I came up with - the trick was that I couldn't check the file size directly as that made the Fog RubyGem bomb if the file hadn't been uploaded. I would expect there to be a cleaner way to ask CarrierWave if a file was uploaded.

Peter Marklund
  • 1,033
  • 10
  • 9