Github url


by carrierwaveuploader

carrierwaveuploader /carrierwave

Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks

8.5K Stars 1.5K Forks Last release: over 6 years ago (v0.10.0) 2.4K Commits 60 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:


This gem provides a simple and extremely flexible way to upload files from Ruby applications. It works well with Rack based web applications, such as Ruby on Rails.

Build StatusCode ClimateSemVer


Getting Help

  • Please ask the community on Stack Overflow for help if you have any questions. Please do not post usage questions on the issue tracker.
  • Please report bugs on the issue tracker but read the "getting help" section in the wiki first.


Install the latest release:

$ gem install carrierwave

In Rails, add it to your Gemfile:

gem 'carrierwave', '~\> 2.0'

Finally, restart the server to apply the changes.

As of version 2.0, CarrierWave requires Rails 5.0 or higher and Ruby 2.2 or higher. If you're on Rails 4, you should use 1.x.

Getting Started

Start off by generating an uploader:

rails generate uploader Avatar

this should give you a file in:


Check out this file for some hints on how you can customize your uploader. It should look something like this:

class AvatarUploader \< CarrierWave::Uploader::Base storage :file end

You can use your uploader class to store and retrieve files like this:

uploader =!(my\_file) uploader.retrieve\_from\_store!('my\_file.png')

CarrierWave gives you a


for permanent storage, and a


for temporary storage. You can use different stores, including filesystem and cloud storage.

Most of the time you are going to want to use CarrierWave together with an ORM. It is quite simple to mount uploaders on columns in your model, so you can simply assign files and get going:


Make sure you are loading CarrierWave after loading your ORM, otherwise you'll need to require the relevant extension manually, e.g.:

require 'carrierwave/orm/activerecord'

Add a string column to the model you want to mount the uploader by creating a migration:

rails g migration add\_avatar\_to\_users avatar:string rails db:migrate

Open your model file and mount the uploader:

class User \< ActiveRecord::Base mount\_uploader :avatar, AvatarUploader end

Now you can cache files by assigning them to the attribute, they will automatically be stored when the record is saved.

u = u.avatar = params[:file] # Assign a file like this, or # like this'somewhere') do |f| u.avatar = f end! u.avatar.url # =\> '/url/to/file.png' u.avatar.current\_path # =\> 'path/to/file.png' u.avatar\_identifier # =\> 'file.png'



will never return nil, even if there is no photo associated to it. To check if a photo was saved to the model, use



DataMapper, Mongoid, Sequel

Other ORM support has been extracted into separate gems:

There are more extensions listed in the wiki

Multiple file uploads

CarrierWave also has convenient support for multiple file upload fields.


Add a column which can store an array. This could be an array column or a JSON column for example. Your choice depends on what your database supports. For example, create a migration like this:

For databases with ActiveRecord json data type support (e.g. PostgreSQL, MySQL)

rails g migration add\_avatars\_to\_users avatars:json rails db:migrate

For database without ActiveRecord json data type support (e.g. SQLite)

rails g migration add\_avatars\_to\_users avatars:string rails db:migrate

Note: JSON datatype doesn't exists in SQLite adapter, that's why you can use a string datatype which will be serialized in model.

Open your model file and mount the uploader:

class User \< ActiveRecord::Base mount\_uploaders :avatars, AvatarUploader serialize :avatars, JSON # If you use SQLite, add this line. end

Make sure that you mount the uploader with write (mount_uploaders) with


not (mount_ uploader) in order to avoid errors when uploading multiple files

Make sure your file input fields are set up as multiple file fields. For example in Rails you'll want to do something like this:

Also, make sure your upload controller permits the multiple file upload attribute, pointing to an empty array in a hash. For example:

params.require(:user).permit(:email, :first\_name, :last\_name, {avatars: []})

Now you can select multiple files in the upload dialog (e.g. SHIFT+SELECT), and they will automatically be stored when the record is saved.

u =[:user])! u.avatars[0].url # =\> '/url/to/file.png' u.avatars[0].current\_path # =\> 'path/to/file.png' u.avatars[0].identifier # =\> 'file.png'

If you want to preserve existing files on uploading new one, you can go like:

Sorting avatars is supported as well by reordering


, an example using jQuery UI Sortable is available here.

Changing the storage directory

In order to change where uploaded files are put, just override the



class MyUploader \< CarrierWave::Uploader::Base def store\_dir 'public/my/upload/directory' end end

This works for the file storage as well as Amazon S3 and Rackspace Cloud Files. Define




if you'd like to store files at the root level.

If you store files outside the project root folder, you may want to define


in the same way:

class MyUploader \< CarrierWave::Uploader::Base def cache\_dir '/tmp/projectname-cache' end end

Securing uploads

Certain files might be dangerous if uploaded to the wrong location, such as PHP files or other script files. CarrierWave allows you to specify a whitelist of allowed extensions or content types.

If you're mounting the uploader, uploading a file with the wrong extension will make the record invalid instead. Otherwise, an error is raised.

class MyUploader \< CarrierWave::Uploader::Base def extension\_whitelist %w(jpg jpeg gif png) end end

The same thing could be done using content types. Let's say we need an uploader that accepts only images. This can be done like this

class MyUploader \< CarrierWave::Uploader::Base def content\_type\_whitelist /image\// end end

You can use a blacklist to reject content types. Let's say we need an uploader that reject JSON files. This can be done like this

class NoJsonUploader \< CarrierWave::Uploader::Base def content\_type\_blacklist ['application/text', 'application/json'] end end

CVE-2016-3714 (ImageTragick)

This version of CarrierWave has the ability to mitigate CVE-2016-3714. However, you MUST set a content_type_whitelist in your uploaders for this protection to be effective, and you MUST either disable ImageMagick's default SVG delegate or use the RSVG delegate for SVG processing.

A valid whitelist that will restrict your uploader to images only, and mitigate the CVE is:

class MyUploader \< CarrierWave::Uploader::Base def content\_type\_whitelist [/image\//] end end



is the only form of whitelist or blacklist supported by CarrierWave that can effectively mitigate against CVE-2016-3714. Use of


will not inspect the file headers, and thus still leaves your application open to the vulnerability.

Filenames and unicode chars

Another security issue you should care for is the file names (seeRuby On Rails Security Guide). By default, CarrierWave provides only English letters, arabic numerals and some symbols as white-listed characters in the file name. If you want to support local scripts (Cyrillic letters, letters with diacritics and so on), you have to override


method. It should return regular expression which would match all non-allowed symbols.

CarrierWave::SanitizedFile.sanitize\_regexp = /[^[:word:]\.\-\+]/

Also make sure that allowing non-latin characters won't cause a compatibility issue with a third-party plugins or client-side software.

Setting the content type

As of v0.11.0, the


gem is a runtime dependency and the content type is set automatically. You no longer need to do this manually.

Adding versions

Often you'll want to add different versions of the same file. The classic example is image thumbnails. There is built in support for this*:

Note: You must have Imagemagick installed to do image resizing.

Some documentation refers to RMagick instead of MiniMagick but MiniMagick is recommended.

To install Imagemagick on OSX with homebrew type the following:

$ brew install imagemagick
class MyUploader \< CarrierWave::Uploader::Base include CarrierWave::MiniMagick process resize\_to\_fit: [800, 800] version :thumb do process resize\_to\_fill: [200,200] end end

When this uploader is used, an uploaded image would be scaled to be no larger than 800 by 800 pixels. The original aspect ratio will be kept.

A version called


is then created, which is scaled to exactly 200 by 200 pixels. The thumbnail uses


which makes sure that the width and height specified are filled, only cropping if the aspect ratio requires it.

The above uploader could be used like this:

uploader =!(my\_file) # size: 1024x768 uploader.url # =\> '/url/to/my\_file.png' # size: 800x800 uploader.thumb.url # =\> '/url/to/thumb\_my\_file.png' # size: 200x200

One important thing to remember is that process is called before versions are created. This can cut down on processing cost.

Processing Methods: mini_magick

  • convert
    • Changes the image encoding format to the given format, eg. jpg
  • resize\_to\_limit
    • Resize the image to fit within the specified dimensions while retaining the original aspect ratio. Will only resize the image if it is larger than the specified dimensions. The resulting image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.
  • resize\_to\_fit
    • Resize the image to fit within the specified dimensions while retaining the original aspect ratio. The image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.
  • resize\_to\_fill
    • Resize the image to fit within the specified dimensions while retaining the aspect ratio of the original image. If necessary, crop the image in the larger dimension. Optionally, a "gravity" may be specified, for example "Center", or "NorthEast".
  • resize\_and\_pad
    • Resize the image to fit within the specified dimensions while retaining the original aspect ratio. If necessary, will pad the remaining area with the given color, which defaults to transparent (for gif and png, white for jpeg). Optionally, a "gravity" may be specified, as above.



for details.

Nested versions

It is possible to nest versions within versions:

class MyUploader \< CarrierWave::Uploader::Base version :animal do version :human version :monkey version :llama end end

Conditional versions

Occasionally you want to restrict the creation of versions on certain properties within the model or based on the picture itself.

class MyUploader \< CarrierWave::Uploader::Base version :human, if: :is\_human? version :monkey, if: :is\_monkey? version :banner, if: :is\_landscape? private def is\_human? picture model.can\_program?(:ruby) end def is\_monkey? picture model.favorite\_food == 'banana' end def is\_landscape? picture image = image[:width] \> image[:height] end end



variable points to the instance object the uploader is attached to.

Create versions from existing versions

For performance reasons, it is often useful to create versions from existing ones instead of using the original file. If your uploader generates several versions where the next is smaller than the last, it will take less time to generate from a smaller, already processed image.

class MyUploader \< CarrierWave::Uploader::Base version :thumb do process resize\_to\_fill: [280, 280] end version :small\_thumb, from\_version: :thumb do process resize\_to\_fill: [20, 20] end end

The option


uses the file cached in the


version instead of the original version, potentially resulting in faster processing.

Making uploads work across form redisplays

Often you'll notice that uploaded files disappear when a validation fails. CarrierWave has a feature that makes it easy to remember the uploaded file even in that case. Suppose your


model has an uploader mounted on


file, just add a hidden field called


(don't forget to add it to the attr_accessible list as necessary). In Rails, this would look like this:

<label>My Avatar</label>

It might be a good idea to show the user that a file has been uploaded, in the case of images, a small thumbnail would be a good indicator:

<label>My Avatar</label>

Removing uploaded files

If you want to remove a previously uploaded file on a mounted uploader, you can easily add a checkbox to the form which will remove the file when checked.

<label>My Avatar</label>


      Remove avatar

If you want to remove the file manually, you can call remove_avatar!, then save the object.

@user.remove\_avatar! #=\> true

Uploading files from a remote location

Your users may find it convenient to upload a file from a location on the Internet via a URL. CarrierWave makes this simple, just add the appropriate attribute to your form and you're good to go:

<label>My Avatar URL:</label>

If you're using ActiveRecord, CarrierWave will indicate invalid URLs and download failures automatically with attribute validation errors. If you aren't, or you disable CarrierWave's


option, you'll need to handle those errors yourself.

Providing a default URL

In many cases, especially when working with images, it might be a good idea to provide a default url, a fallback in case no file has been uploaded. You can do this easily by overriding the


method in your uploader:

class MyUploader \< CarrierWave::Uploader::Base def default\_url(\*args) "/images/fallback/" + [version\_name, "default.png"].compact.join('\_') end end

Or if you are using the Rails asset pipeline:

class MyUploader \< CarrierWave::Uploader::Base def default\_url(\*args) ActionController::Base.helpers.asset\_path("fallback/" + [version\_name, "default.png"].compact.join('\_')) end end

Recreating versions

You might come to a situation where you want to retroactively change a version or add a new one. You can use the


method to recreate the versions from the base file. This uses a naive approach which will re-upload and process the specified version or all versions, if none is passed as an argument.

When you are generating random unique filenames you have to call


on the model after using


. This is necessary because


doesn't save the new filename to the database. Calling


yourself will prevent that the database and file system are running out of sync.

instance = instance.recreate\_versions!(:thumb, :large)

Or on a mounted uploader:

User.find\_each do |user| user.avatar.recreate\_versions! end



will throw an exception on records without an image. To avoid this, scope the records to those with images or check if an image exists within the block. If you're using ActiveRecord, recreating versions for a user avatar might look like this:

User.find\_each do |user| user.avatar.recreate\_versions! if user.avatar? end

Configuring CarrierWave

CarrierWave has a broad range of configuration options, which you can configure, both globally and on a per-uploader basis:

CarrierWave.configure do |config| config.permissions = 0666\_permissions = 0777 = :file end

Or alternatively:

class AvatarUploader \< CarrierWave::Uploader::Base permissions 0777 end

If you're using Rails, create an initializer for this:


If you want CarrierWave to fail noisily in development, you can change these configs in your environment file:

CarrierWave.configure do |config| config.ignore\_integrity\_errors = false config.ignore\_processing\_errors = false config.ignore\_download\_errors = false end

Testing with CarrierWave

It's a good idea to test your uploaders in isolation. In order to speed up your tests, it's recommended to switch off processing in your tests, and to use the file storage. In Rails you could do that by adding an initializer with:

if Rails.env.test? or Rails.env.cucumber? CarrierWave.configure do |config| = :file config.enable\_processing = false end end

Remember, if you have already set

storage :something

in your uploader, the


setting from this initializer will be ignored.

If you need to test your processing, you should test it in isolation, and enable processing only for those tests that need it.

CarrierWave comes with some RSpec matchers which you may find useful:

require 'carrierwave/test/matchers' describe MyUploader do include CarrierWave::Test::Matchers let(:user) { double('user') } let(:uploader) {, :avatar) } before do MyUploader.enable\_processing = true\_to\_file) { |f|!(f) } end after do MyUploader.enable\_processing = false uploader.remove! end context 'the thumb version' do it "scales down a landscape image to be exactly 64 by 64 pixels" do expect(uploader.thumb).to have\_dimensions(64, 64) end end context 'the small version' do it "scales down a landscape image to fit within 200 by 200 pixels" do expect(uploader.small).to be\_no\_larger\_than(200, 200) end end it "makes the image readable only to the owner and not executable" do expect(uploader).to have\_permissions(0600) end it "has the correct format" do expect(uploader).to be\_format('png') end end

If you're looking for minitest asserts, checkout carrierwave_asserts.

Setting the enable_processing flag on an uploader will prevent any of the versions from processing as well. Processing can be enabled for a single version by setting the processing flag on the version like so:

@uploader.thumb.enable\_processing = true


If you want to use fog you must add in your CarrierWave initializer the following lines

config.fog\_credentials = { ... } # Provider specific credentials

Using Amazon S3

Fog AWS is used to support Amazon S3. Ensure you have it in your Gemfile:

gem "fog-aws"

You'll need to provide your fog_credentials and a fog_directory (also known as a bucket) in an initializer. For the sake of performance it is assumed that the directory already exists, so please create it if it needs to be. You can also pass in additional options, as documented fully in lib/carrierwave/storage/fog.rb. Here's a full example:

CarrierWave.configure do |config| config.fog\_credentials = { provider: 'AWS', # required aws\_access\_key\_id: 'xxx', # required unless using use\_iam\_profile aws\_secret\_access\_key: 'yyy', # required unless using use\_iam\_profile use\_iam\_profile: true, # optional, defaults to false region: 'eu-west-1', # optional, defaults to 'us-east-1' host: '', # optional, defaults to nil endpoint: '' # optional, defaults to nil } config.fog\_directory = 'name\_of\_bucket' # required config.fog\_public = false # optional, defaults to true config.fog\_attributes = { cache\_control: "public, max-age=#{\_i}" } # optional, defaults to {} end

In your uploader, set the storage to :fog

class AvatarUploader \< CarrierWave::Uploader::Base storage :fog end

That's it! You can still use the


method to return the url to the file on Amazon S3.

Note: for Carrierwave to work properly it needs credentials with the following permissions:

  • s3:ListBucket
  • s3:PutObject
  • s3:GetObject
  • s3:DeleteObject
  • s3:PutObjectAcl

Using Rackspace Cloud Files

Fog is used to support Rackspace Cloud Files. Ensure you have it in your Gemfile:

gem "fog"

You'll need to configure a directory (also known as a container), username and API key in the initializer. For the sake of performance it is assumed that the directory already exists, so please create it if need be.

Using a US-based account:

CarrierWave.configure do |config| config.fog\_credentials = { provider: 'Rackspace', rackspace\_username: 'xxxxxx', rackspace\_api\_key: 'yyyyyy', rackspace\_region: :ord # optional, defaults to :dfw } config.fog\_directory = 'name\_of\_directory' end

Using a UK-based account:

CarrierWave.configure do |config| config.fog\_credentials = { provider: 'Rackspace', rackspace\_username: 'xxxxxx', rackspace\_api\_key: 'yyyyyy', rackspace\_auth\_url: Fog::Rackspace::UK\_AUTH\_ENDPOINT, rackspace\_region: :lon } config.fog\_directory = 'name\_of\_directory' end

You can optionally include your CDN host name in the configuration. This is highly recommended, as without it every request requires a lookup of this information.

config.asset\_host = ""

In your uploader, set the storage to :fog

class AvatarUploader \< CarrierWave::Uploader::Base storage :fog end

That's it! You can still use the


method to return the url to the file on Rackspace Cloud Files.

Using Google Storage for Developers

Fog is used to support Google Storage for Developers. Ensure you have it in your Gemfile:

gem "fog-google" gem "google-api-client", "\> 0.8.5", "\< 0.9" gem "mime-types"

You'll need to configure a directory (also known as a bucket), access key id and secret access key in the initializer. For the sake of performance it is assumed that the directory already exists, so please create it if need be.

Please read the fog-google README on how to get credentials.

CarrierWave.configure do |config| config.fog\_credentials = { provider: 'Google', google\_storage\_access\_key\_id: 'xxxxxx', google\_storage\_secret\_access\_key: 'yyyyyy' } config.fog\_directory = 'name\_of\_directory' end

In your uploader, set the storage to :fog

class AvatarUploader \< CarrierWave::Uploader::Base storage :fog end

That's it! You can still use the


method to return the url to the file on Google.

Optimized Loading of Fog

Since Carrierwave doesn't know which parts of Fog you intend to use, it will just load the entire library (unless you use e.g. [




] instead of fog proper). If you prefer to load fewer classes into your application, you need to load those parts of Fog yourself before loading CarrierWave in your Gemfile. Ex:

gem "fog", "~\> 1.27", require: "fog/rackspace/storage" gem "carrierwave"

A couple of notes about versions: * This functionality was introduced in Fog v1.20. * This functionality is slated for CarrierWave v1.0.0.

If you're not relying on Gemfile entries alone and are requiring "carrierwave" anywhere, ensure you require "fog/rackspace/storage" before it. Ex:

require "fog/rackspace/storage" require "carrierwave"

Beware that this specific require is only needed when working with a fog provider that was not extracted to its own gem yet. A list of the extracted providers can be found in the page of the


organizations here.

When in doubt, inspect


to see what has been loaded.

Dynamic Asset Host



config property can be assigned a proc (or anything that responds to


) for generating the host dynamically. The proc-compliant object gets an instance of the current




as its only argument.

CarrierWave.configure do |config| config.asset\_host = proc do |file| identifier = # some logic "http://#{identifier}" end end

Using RMagick

If you're uploading images, you'll probably want to manipulate them in some way, you might want to create thumbnail images for example. CarrierWave comes with a small library to make manipulating images with RMagick easier, you'll need to include it in your Uploader:

class AvatarUploader \< CarrierWave::Uploader::Base include CarrierWave::RMagick end

The RMagick module gives you a few methods, like


which manipulate the image file in some way. You can set a


callback, which will call that method any time a file is uploaded. There is a demonstration of convert here. Convert will only work if the file has the same file extension, thus the use of the filename method.

class AvatarUploader \< CarrierWave::Uploader::Base include CarrierWave::RMagick process resize\_to\_fill: [200, 200] process convert: 'png' def filename super.chomp(File.extname(super)) + '.png' if original\_filename.present? end end

Check out the manipulate! method, which makes it easy for you to write your own manipulation methods.

Using MiniMagick

MiniMagick is similar to RMagick but performs all the operations using the 'convert' CLI which is part of the standard ImageMagick kit. This allows you to have the power of ImageMagick without having to worry about installing all the RMagick libraries.

See the MiniMagick site for more details:

And the ImageMagick command line options for more for whats on offer:

Currently, the MiniMagick carrierwave processor provides exactly the same methods as for the RMagick processor.

class AvatarUploader \< CarrierWave::Uploader::Base include CarrierWave::MiniMagick process resize\_to\_fill: [200, 200] end

Migrating from Paperclip

If you are using Paperclip, you can use the provided compatibility module:

class AvatarUploader \< CarrierWave::Uploader::Base include CarrierWave::Compatibility::Paperclip end

See the documentation for


for more details.

Be sure to use mount_on to specify the correct column:

mount\_uploader :avatar, AvatarUploader, mount\_on: :avatar\_file\_name


The Active Record validations use the Rails


framework. Add these keys to your translations file:

errors: messages: carrierwave\_processing\_error: failed to be processed carrierwave\_integrity\_error: is not of an allowed file type carrierwave\_download\_error: could not be downloaded extension\_whitelist\_error: "You are not allowed to upload %{extension} files, allowed types: %{allowed\_types}" extension\_blacklist\_error: "You are not allowed to upload %{extension} files, prohibited types: %{prohibited\_types}" content\_type\_whitelist\_error: "You are not allowed to upload %{content\_type} files, allowed types: %{allowed\_types}" content\_type\_blacklist\_error: "You are not allowed to upload %{content\_type} files" rmagick\_processing\_error: "Failed to manipulate with rmagick, maybe it is not an image?" mini\_magick\_processing\_error: "Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: %{e}" min\_size\_error: "File size should be greater than %{min\_size}" max\_size\_error: "File size should be less than %{max\_size}"

The [


]( adds support for additional locales.

Large files

By default, CarrierWave copies an uploaded file twice, first copying the file into the cache, then copying the file into the store. For large files, this can be prohibitively time consuming.

You may change this behavior by overriding either or both of the





class MyUploader \< CarrierWave::Uploader::Base def move\_to\_cache true end def move\_to\_store true end end

When the




methods return true, files will be moved (instead of copied) to the cache and store respectively.

This has only been tested with the local filesystem store.

Skipping ActiveRecord callbacks

By default, mounting an uploader into an ActiveRecord model will add a few callbacks. For example, this code:

class User mount\_uploader :avatar, AvatarUploader end

Will add these callbacks:

before\_save :write\_avatar\_identifier after\_save :store\_previous\_changes\_for\_avatar after\_commit :remove\_avatar!, on: :destroy after\_commit :mark\_remove\_avatar\_false, on: :update after\_commit :remove\_previously\_stored\_avatar, on: :update after\_commit :store\_avatar!, on: [:create, :update]

If you want to skip any of these callbacks (eg. you want to keep the existing avatar, even after uploading a new one), you can use ActiveRecord’s



class User mount\_uploader :avatar, AvatarUploader skip\_callback :commit, :after, :remove\_previously\_stored\_avatar end

Contributing to CarrierWave



Copyright (c) 2008-2015 Jonas Nicklas

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.