jpemberthy
jpemberthy

Reputation: 7533

validate size of upload using Carrierwave

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!

Upvotes: 18

Views: 21328

Answers (4)

Alex Kojin
Alex Kojin

Reputation: 5204

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

Upvotes: 5

Musaffa
Musaffa

Reputation: 702

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.

Upvotes: 5

Peter Marklund
Peter Marklund

Reputation: 1033

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.

Upvotes: -1

Flov
Flov

Reputation: 1587

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

Upvotes: 22

Related Questions