Javascript required
Skip to content Skip to sidebar Skip to footer

Upload Multiple Files Carrierwave Ruby on Rails

CarrierWave

This jewel 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 Status Code Climate SemVer

Data

  • RDoc documentation available on RubyDoc.info
  • Source code available on GitHub
  • More than information, known limitations, and how-tos available on the wiki

Getting Assist

  • Delight ask the community on Stack Overflow for help if y'all have any questions. Please do not post usage questions on the issue tracker.
  • Please report bugs on the result tracker but read the "getting aid" section in the wiki beginning.

Installation

Install the latest release:

              $ gem install carrierwave                          

In Rail, add it to your Gemfile:

              gem              'carrierwave'              ,              '~> ii.0'            

Finally, restart the server to apply the changes.

As of version ii.0, CarrierWave requires Rails 5.0 or higher and Cerise 2.two or higher. If you're on Runway 4, you should use 1.x.

Getting Started

Start off by generating an uploader:

              runway generate uploader Avatar                          

this should give you a file in:

              app/uploaders/avatar_uploader.rb                          

Bank check out this file for some hints on how you can customize your uploader. It should expect something like this:

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

Y'all tin use your uploader class to store and retrieve files similar this:

              uploader              =              AvatarUploader              .              new              uploader              .              store!              (              my_file              )              uploader              .              retrieve_from_store!              (              'my_file.png'              )            

CarrierWave gives you a shop for permanent storage, and a enshroud for temporary storage. You can utilise different stores, including filesystem and cloud storage.

Well-nigh of the time you are going to want to utilize CarrierWave together with an ORM. It is quite simple to mount uploaders on columns in your model, and then you can simply assign files and become going:

ActiveRecord

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

              require              'carrierwave/orm/activerecord'            

Add together a cord column to the model y'all want to mount the uploader by creating a migration:

              rail g migration add_avatar_to_users avatar:cord rails db:migrate                          

Open your model file and mountain the uploader:

              class              User              <              ApplicationRecord              mount_uploader              :avatar              ,              AvatarUploader              end            

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

              u              =              User              .              new              u              .              avatar              =              params              [              :file              ]              # Assign a file like this, or              # like this              File              .              open up              (              'somewhere'              )              practise              |f|              u              .              avatar              =              f              terminate              u              .              save!              u              .              avatar              .              url              # => '/url/to/file.png'              u              .              avatar              .              current_path              # => 'path/to/file.png'              u              .              avatar_identifier              # => 'file.png'            

Annotation: u.avatar will never render nil, even if there is no photo associated to it. To check if a photo was saved to the model, utilise u.avatar.file.nil? instead.

DataMapper, Mongoid, Sequel

Other ORM back up has been extracted into separate gems:

  • carrierwave-datamapper
  • carrierwave-mongoid
  • carrierwave-sequel

In that location are more extensions listed in the wiki

Multiple file uploads

CarrierWave as well has user-friendly back up for multiple file upload fields.

ActiveRecord

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

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

              rails g migration add_avatars_to_users avatars:json runway db:migrate                          

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

              rails m migration add_avatars_to_users avatars:string rails db:migrate                          

Note: JSON datatype doesn't exists in SQLite adapter, that'south why you lot tin use a cord datatype which will be serialized in model.

Open up your model file and mount the uploader:

              class              User              <              ApplicationRecord              mount_uploaders              :avatars              ,              AvatarUploader              serialize              :avatars              ,              JSON              # If you use SQLite, add together this line.              finish            

Brand sure that y'all mountain the uploader with write (mount_uploaders) with s not (mount_uploader) in order to avoid errors when uploading multiple files

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

              <%=              form.file_field :avatars, multiple: true              %>                                                                                                              

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 tin select multiple files in the upload dialog (e.grand. SHIFT+SELECT), and they will automatically be stored when the record is saved.

              u              =              User              .              new              (              params              [              :user              ]              )              u              .              salve!              u              .              avatars              [              0              ]              .              url              # => '/url/to/file.png'              u              .              avatars              [              0              ]              .              current_path              # => 'path/to/file.png'              u              .              avatars              [              0              ]              .              identifier              # => 'file.png'            

If y'all want to preserve existing files on uploading new one, you can get similar:

              <%              user.avatars.each exercise |avatar|              %>                                            <%=              hidden_field :user, :avatars, multiple: true, value: avatar.identifier              %>                            <%              finish              %>                            <%=              form.file_field :avatars, multiple: truthful              %>                                                                                                                                                                                                                                                                                                                                                                                                      

Sorting avatars is supported as well by reordering hidden_field, an example using jQuery UI Sortable is available hither.

Changing the storage directory

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

              class              MyUploader              <              CarrierWave::Uploader::Base              def              store_dir              'public/my/upload/directory'              end              end            

This works for the file storage also as Amazon S3 and Rackspace Cloud Files. Define store_dir equally nil if you'd like to store files at the root level.

If you lot store files exterior the project root binder, you may want to ascertain cache_dir in the same way:

              class              MyUploader              <              CarrierWave::Uploader::Base of operations              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 an allowlist 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.

              form              MyUploader              <              CarrierWave::Uploader::Base              def              extension_allowlist              %due west(              jpg              jpeg              gif              png              )              stop              end            

The aforementioned 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 of operations              def              content_type_allowlist              /epitome\//              finish              stop            

You tin can use a denylist to reject content types. Allow's say we demand an uploader that pass up JSON files. This can be done like this

              class              NoJsonUploader              <              CarrierWave::Uploader::Base              def              content_type_denylist              [              'application/text'              ,              'application/json'              ]              cease              end            

CVE-2016-3714 (ImageTragick)

This version of CarrierWave has the ability to mitigate CVE-2016-3714. Nonetheless, yous MUST set up a content_type_allowlist 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 allowlist that will restrict your uploader to images only, and mitigate the CVE is:

              form              MyUploader              <              CarrierWave::Uploader::Base of operations              def              content_type_allowlist              [              /image\//              ]              end              terminate            

Alert: A content_type_allowlist is the only form of allowlist or denylist supported by CarrierWave that can effectively mitigate against CVE-2016-3714. Use of extension_allowlist will not audit the file headers, and thus nevertheless leaves your application open to the vulnerability.

Filenames and unicode chars

Another security issue you should care for is the file names (see Cherry On Rail Security Guide). By default, CarrierWave provides but English letters, standard arabic numerals and some symbols as allowlisted characters in the file name. If you want to support local scripts (Cyrillic letters, messages with diacritics and so on), you accept to override sanitize_regexp method. It should return regular expression which would friction match all non-allowed symbols.

              CarrierWave::SanitizedFile              .              sanitize_regexp              =              /[^[:discussion:]\.                \-                \+]/            

Also make sure that assuasive not-latin characters won't crusade a compatibility outcome with a tertiary-political party plugins or client-side software.

Setting the content blazon

As of v0.xi.0, the mime-types gem is a runtime dependency and the content type is set automatically. You no longer need to exercise this manually.

Adding versions

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

Note: You lot must have Imagemagick installed to practise image resizing.

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

To install Imagemagick on OSX with homebrew blazon the following:

              $ brew install imagemagick                          
              class              MyUploader              <              CarrierWave::Uploader::Base of operations              include              CarrierWave::MiniMagick              process              resize_to_fit:              [              800              ,              800              ]              version              :pollex              practice              process              resize_to_fill:              [              200              ,              200              ]              finish              cease            

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

A version chosen :thumb is then created, which is scaled to exactly 200 by 200 pixels. The thumbnail uses resize_to_fill which makes sure that the width and summit specified are filled, merely cropping if the aspect ratio requires it.

The above uploader could be used like this:

              uploader              =              AvatarUploader              .              new              uploader              .              store!              (              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 procedure is called before versions are created. This tin can cut downwards on processing cost.

Processing Methods: mini_magick

  • convert - Changes the prototype 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 but resize the paradigm if it is larger than the specified dimensions. The resulting image may be shorter or narrower than specified in the smaller dimension just will not be larger than the specified values.
  • resize_to_fit - Resize the epitome to fit within the specified dimensions while retaining the original attribute ratio. The image may be shorter or narrower than specified in the smaller dimension just will not exist 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 epitome. If necessary, ingather the prototype 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 expanse with the given colour, which defaults to transparent (for gif and png, white for jpeg). Optionally, a "gravity" may exist specified, as to a higher place.

Run across carrierwave/processing/mini_magick.rb for details.

conditional process

If you lot want to use conditional process, you lot tin simply use if statement.

See carrierwave/uploader/processing.rb for details.

              class              MyUploader              <              CarrierWave::Uploader::Base              process              :scale              =>              [              200              ,              200              ]              ,              :if              =>              :prototype?              def              paradigm?              (              carrier_wave_sanitized_file              )              truthful              finish              cease            

Nested versions

It is possible to nest versions within versions:

              course              MyUploader              <              CarrierWave::Uploader::Base              version              :brute              do              version              :human              version              :monkey              version              :llama              cease              terminate            

Provisional versions

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

              class              MyUploader              <              CarrierWave::Uploader::Base of operations              version              :human              ,              if:              :is_human?              version              :monkey              ,              if:              :is_monkey?              version              :banner              ,              if:              :is_landscape?              individual              def              is_human?              picture              model              .              can_program?              (              :scarlet              )              terminate              def              is_monkey?              picture              model              .              favorite_food              ==              'banana'              end              def              is_landscape?              moving-picture show              image              =              MiniMagick::Epitome              .              new              (              picture              .              path              )              image              [              :width              ]              >              epitome              [              :acme              ]              stop              end            

The model variable points to the example object the uploader is attached to.

Create versions from existing versions

For functioning reasons, information technology 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 terminal, information technology will take less time to generate from a smaller, already processed paradigm.

              form              MyUploader              <              CarrierWave::Uploader::Base              version              :thumb              do              process              resize_to_fill:              [              280              ,              280              ]              finish              version              :small_thumb              ,              from_version:              :thumb              practice              process              resize_to_fill:              [              twenty              ,              20              ]              end              end            

The option :from_version uses the file cached in the :thumb version instead of the original version, potentially resulting in faster processing.

Making uploads work beyond form redisplays

Often you'll discover that uploaded files disappear when a validation fails. CarrierWave has a feature that makes it piece of cake to remember the uploaded file even in that example. Suppose your user model has an uploader mounted on avatar file, just add together a hidden field called avatar_cache (don't forget to add it to the attr_accessible list every bit necessary). In Rails, this would look like this:

              <%=              form_for @user, html: { multipart: true } do |f|              %>                                                                                                                                                                              <              p              >              <              label              >My Avatar</              label              >              <%=              f              .              file_field              :avatar              %>                                            <%=              f              .              hidden_field              :avatar_cache              %>              </              p              >              <%              cease              %>            

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

              <%=              form_for @user, html: { multipart: true } do |f|              %>                                                                                                                                                                              <              p              >              <              label              >My Avatar</              label              >              <%=              image_tag              (              @user              .              avatar_url              )              if              @user              .              avatar?              %>                                            <%=              f              .              file_field              :avatar              %>                                            <%=              f              .              hidden_field              :avatar_cache              %>              </              p              >              <%              end              %>            

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.

              <%=              form_for @user, html: { multipart: true } do |f|              %>                                                                                                                                                                              <              p              >              <              label              >My Avatar</              label              >              <%=              image_tag              (              @user              .              avatar_url              )              if              @user              .              avatar?              %>                                            <%=              f              .              file_field              :avatar              %>              </              p              >              <              p              >              <              characterization              >              <%=              f              .              check_box              :remove_avatar              %>              Remove avatar              </              label              >              </              p              >              <%              end              %>            

If y'all desire to remove the file manually, yous tin call remove_avatar!, then salvage the object.

@user.remove_avatar! @user.save #=>              true

Uploading files from a remote location

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

              <%=              form_for @user, html: { multipart: true } exercise |f|              %>                                                                                                                                                                              <              p              >              <              characterization              >My Avatar URL:</              label              >              <%=              image_tag              (              @user              .              avatar_url              )              if              @user              .              avatar?              %>                                            <%=              f              .              text_field              :remote_avatar_url              %>              </              p              >              <%              end              %>            

If you're using ActiveRecord, CarrierWave will betoken invalid URLs and download failures automatically with attribute validation errors. If you aren't, or you disable CarrierWave's validate_download option, y'all'll demand to handle those errors yourself.

Retry choice for download from remote location

If you want to retry the download from the Remote URL, enable the download_retry_count selection, an error occurs during download, information technology will try to execute the specified number of times every 5 second. This pick is constructive when the remote destination is unstable.

              CarrierWave              .              configure              do              |config|              config              .              download_retry_count              =              3              # Default 0              end            

Providing a default URL

In many cases, especially when working with images, information technology might be a good thought to provide a default url, a fallback in case no file has been uploaded. You tin can exercise this hands by overriding the default_url method in your uploader:

              grade              MyUploader              <              CarrierWave::Uploader::Base              def              default_url              (*args              )              "/images/fallback/"              +              [              version_name              ,              "default.png"              ]              .              compact              .              bring together              (              '_'              )              stop              cease            

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              (              '_'              )              )              finish              end            

Recreating versions

Yous might come to a situation where you desire to retroactively change a version or add a new 1. You can use the recreate_versions! 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 every bit an argument.

When you lot are generating random unique filenames yous have to telephone call save! on the model later using recreate_versions!. This is necessary because recreate_versions! doesn't save the new filename to the database. Calling salvage! yourself will foreclose that the database and file organisation are running out of sync.

              instance              =              MyUploader              .              new              instance              .              recreate_versions!              (              :thumb              ,              :large              )            

Or on a mounted uploader:

              User              .              find_each              exercise              |user|              user              .              avatar              .              recreate_versions!              terminate            

Note: recreate_versions! 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 cake. If y'all're using ActiveRecord, recreating versions for a user avatar might look similar 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 footing:

              CarrierWave              .              configure              do              |config|              config              .              permissions              =              0666              config              .              directory_permissions              =              0777              config              .              storage              =              :file              end            

Or alternatively:

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

If yous're using Runway, create an initializer for this:

              config/initializers/carrierwave.rb                          

If you desire CarrierWave to neglect noisily in development, yous can change these configs in your surround file:

              CarrierWave              .              configure              do              |config|              config              .              ignore_integrity_errors              =              fake              config              .              ignore_processing_errors              =              false              config              .              ignore_download_errors              =              simulated              finish            

Testing with CarrierWave

It'south a proficient idea to test your uploaders in isolation. In gild to speed upwardly your tests, information technology's recommended to switch off processing in your tests, and to use the file storage. In Rail yous could do that past calculation an initializer with:

              if              Rails              .              env              .              test?              or              Track              .              env              .              cucumber?              CarrierWave              .              configure              do              |config|              config              .              storage              =              :file              config              .              enable_processing              =              false              end              end            

Remember, if you accept already set storage :something in your uploader, the storage setting from this initializer will be ignored.

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

CarrierWave comes with some RSpec matchers which y'all may find useful:

              require              'carrierwave/test/matchers'              describe              MyUploader              practice              include              CarrierWave::Test::Matchers              let              (              :user              )              {              double              (              'user'              )              }              permit              (              :uploader              )              {              MyUploader              .              new              (              user              ,              :avatar              )              }              before              do              MyUploader              .              enable_processing              =              true              File              .              open              (              path_to_file              )              {              |f|              uploader              .              shop!              (              f              )              }              end              later on              exercise              MyUploader              .              enable_processing              =              false              uploader              .              remove!              stop              context              'the thumb version'              practice              information technology              "scales downwardly a landscape paradigm to be exactly 64 by 64 pixels"              do              expect              (              uploader              .              thumb              )              .              to              have_dimensions              (              64              ,              64              )              stop              end              context              'the small version'              do              it              "scales downwardly a landscape image to fit within 200 past 200 pixels"              do              expect              (              uploader              .              small              )              .              to              be_no_larger_than              (              200              ,              200              )              finish              end              information technology              "makes the image readable simply to the owner and not executable"              do              expect              (              uploader              )              .              to              have_permissions              (              0600              )              end              information technology              "has the correct format"              do              expect              (              uploader              )              .              to              be_format              (              'png'              )              end              end            

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

Setting the enable_processing flag on an uploader will forbid any of the versions from processing too. Processing can be enabled for a unmarried version by setting the processing flag on the version similar and so:

              @uploader              .              thumb              .              enable_processing              =              true            

Fog

If you want to use fog yous must add together 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 accept information technology in your Gemfile:

You'll need to provide your fog_credentials and a fog_directory (besides known as a saucepan) in an initializer. For the sake of performance it is causeless that the directory already exists, so please create it if information technology needs to be. You tin can also pass in additional options, as documented fully in lib/carrierwave/storage/fog.rb. Hither'southward a full case:

              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:              truthful              ,              # optional, defaults to false              region:              'european union-west-1'              ,              # optional, defaults to 'us-due east-1'              host:              's3.case.com'              ,              # optional, defaults to naught              endpoint:              'https://s3.example.com:8080'              # optional, defaults to nil              }              config              .              fog_directory              =              'name_of_bucket'              # required              config              .              fog_public              =              false              # optional, defaults to truthful              config              .              fog_attributes              =              {              cache_control:              "public, max-age=                  #{                  365                  .                  days                  .                  to_i                  }                "              }              # optional, defaults to {}              # For an application which utilizes multiple servers but does not need caches persisted beyond requests,              # uncomment the line :file instead of the default :storage.  Otherwise, it will use AWS as the temp cache shop.              # config.cache_storage = :file              end            

In your uploader, set the storage to :fog

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

That'southward it! You tin still utilise the CarrierWave::Uploader#url method to render the url to the file on Amazon S3.

Note: for Carrierwave to work properly information technology 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 Deject Files. Ensure you have it in your Gemfile:

Yous'll need to configure a directory (also known every bit a container), username and API key in the initializer. For the sake of performance it is causeless that the directory already exists, so please create information technology if need be.

Using a U.s.a.-based business relationship:

              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'              cease            

Using a UK-based business relationship:

              CarrierWave              .              configure              practice              |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'              stop            

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

              config              .              asset_host              =              "http://c000000.cdn.rackspacecloud.com"            

In your uploader, prepare the storage to :fog

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

That's it! You lot can still use the CarrierWave::Uploader#url method to return the url to the file on Rackspace Cloud Files.

Using Google Cloud Storage

Fog is used to back up Google Cloud Storage. Ensure you take it in your Gemfile:

You lot'll need to configure a directory (as well known as a bucket) and the credentials in the initializer. For the sake of performance it is assumed that the directory already exists, so please create information technology if demand be.

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

For Google Storage JSON API (recommended):

              CarrierWave              .              configure              do              |config|              config              .              fog_provider              =              'fog/google'              config              .              fog_credentials              =              {              provider:              'Google'              ,              google_project:              'my-project'              ,              google_json_key_string:              'xxxxxx'              # or use google_json_key_location if using an actual file              }              config              .              fog_directory              =              'google_cloud_storage_bucket_name'              end            

For Google Storage XML API:

              CarrierWave              .              configure              do              |config|              config              .              fog_provider              =              'fog/google'              config              .              fog_credentials              =              {              provider:              'Google'              ,              google_storage_access_key_id:              'xxxxxx'              ,              google_storage_secret_access_key:              'yyyyyy'              }              config              .              fog_directory              =              'google_cloud_storage_bucket_name'              end            

In your uploader, ready the storage to :fog

              grade              AvatarUploader              <              CarrierWave::Uploader::Base              storage              :fog              terminate            

That's information technology! You tin can still use the CarrierWave::Uploader#url 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 utilize, it volition just load the unabridged library (unless you use e.g. [fog-aws, fog-google] instead of fog proper). If you prefer to load fewer classes into your awarding, you need to load those parts of Fog yourself before loading CarrierWave in your Gemfile. Ex:

              gem              "fog"              ,              "~> one.27"              ,              crave:              "fog/rackspace/storage"              gem              "carrierwave"            

A couple of notes virtually 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 crave "fog/rackspace/storage" before information technology. Ex:

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

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

When in doubt, audit Fog.constants to encounter what has been loaded.

Dynamic Nugget Host

The asset_host config holding tin be assigned a proc (or anything that responds to call) for generating the host dynamically. The proc-compliant object gets an case of the electric current CarrierWave::Storage::Fog::File or CarrierWave::SanitizedFile as its but statement.

              CarrierWave              .              configure              practice              |config|              config              .              asset_host              =              proc              do              |file|              identifier              =              # some logic              "http://                  #{                  identifier                  }                .cdn.rackspacecloud.com"              stop              end            

Using RMagick

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

              class              AvatarUploader              <              CarrierWave::Uploader::Base of operations              include              CarrierWave::RMagick              stop            

The RMagick module gives you a few methods, like CarrierWave::RMagick#resize_to_fill which dispense the epitome file in some way. You can ready a process callback, which will call that method any time a file is uploaded. There is a demonstration of catechumen 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              finish            

Check out the manipulate! method, which makes information technology easy for yous to write your own manipulation methods.

Using MiniMagick

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

See the MiniMagick site for more details:

https://github.com/minimagick/minimagick

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

http://world wide web.imagemagick.org/script/command-line-options.php

Currently, the MiniMagick carrierwave processor provides exactly the same methods equally 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 of operations              include              CarrierWave::Compatibility::Paperclip              end            

See the documentation for CarrierWave::Compatibility::Paperclip for more than details.

Be sure to employ mount_on to specify the right cavalcade:

              mount_uploader              :avatar              ,              AvatarUploader              ,              mount_on:              :avatar_file_name            

I18n

The Active Record validations use the Rails i18n framework. Add these keys to your translations file:

              errors:              messages:              carrierwave_processing_error:              failed to exist processed              carrierwave_integrity_error:              is not of an allowed file blazon              carrierwave_download_error:              could not be downloaded              extension_allowlist_error:                              "Yous are not allowed to upload %{extension} files, allowed types: %{allowed_types}"                            extension_denylist_error:                              "You are non allowed to upload %{extension} files, prohibited types: %{prohibited_types}"                            content_type_allowlist_error:                              "You are not allowed to upload %{content_type} files, immune types: %{allowed_types}"                            content_type_denylist_error:                              "You lot are non allowed to upload %{content_type} files"                            processing_error:                              "Failed to manipulate, maybe it is not an image?"                            min_size_error:                              "File size should be greater than %{min_size}"                            max_size_error:                              "File size should be less than %{max_size}"                          

The carrierwave-i18n library adds support for additional locales.

Big files

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

You may alter this beliefs by overriding either or both of the move_to_cache and move_to_store methods:

              class              MyUploader              <              CarrierWave::Uploader::Base              def              move_to_cache              true              terminate              def              move_to_store              true              end              end            

When the move_to_cache and/or move_to_store methods return true, files will exist moved (instead of copied) to the enshroud and store respectively.

This has but been tested with the local filesystem store.

Skipping ActiveRecord callbacks

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

              class              User              mount_uploader              :avatar              ,              AvatarUploader              finish            

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 desire to keep the existing avatar, even subsequently uploading a new 1), you can use ActiveRecord's skip_callback method.

              class              User              mount_uploader              :avatar              ,              AvatarUploader              skip_callback              :commit              ,              :later              ,              :remove_previously_stored_avatar              end            

Uploader Callbacks

In improver to the ActiveRecord callbacks described above, uploaders also have callbacks.

              grade              MyUploader              < ::CarrierWave::Uploader::Base              before              :remove              ,              :log_removal              private              def              log_removal              ::Track              .              logger              .              info              (              format              (              'Deleting file on S3: %due south'              ,              @file              )              )              end              end            

Uploader callbacks tin exist earlier or afterwards the following events:

              cache process remove retrieve_from_cache store                          

Contributing to CarrierWave

Run into CONTRIBUTING.dr.

License

The MIT License (MIT)

Copyright (c) 2008-2015 Jonas Nicklas

Permission is hereby granted, gratis of accuse, to any person obtaining a copy of this software and associated documentation files (the "Software"), to bargain in the Software without restriction, including without limitation the rights to utilise, re-create, change, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do and then, subject field to the following conditions:

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

THE SOFTWARE IS PROVIDED "Every bit IS", WITHOUT WARRANTY OF Whatsoever KIND, EXPRESS OR IMPLIED, INCLUDING BUT Non Express TO THE WARRANTIES OF MERCHANTABILITY, Fitness FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS Exist LIABLE FOR ANY Claim, Amercement OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE Use OR OTHER DEALINGS IN THE SOFTWARE.

heysenaidell.blogspot.com

Source: https://github.com/carrierwaveuploader/carrierwave