Carrierwave Ruby Mount Uploader to Existing Modal

CarrierWave

This gem provides a simple and extremely flexible way to upload files from Crimson applications. Information technology works well with Rack based web applications, such equally Ruddy on Rails.

Build Status Code Climate SemVer

Data

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

Getting Help

  • Please ask the community on Stack Overflow for assist if yous take any questions. Please practice not post usage questions on the upshot tracker.
  • Please report bugs on the result tracker but read the "getting help" section in the wiki first.

Installation

Install the latest release:

              $ gem install carrierwave                          

In Track, add information technology to your Gemfile:

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

Finally, restart the server to apply the changes.

As of version 2.0, CarrierWave requires Rails five.0 or higher and Ruddy 2.two or college. If you're on Rail four, yous should use 1.10.

Getting Started

Outset off by generating an uploader:

              rails generate uploader Avatar                          

this should give you a file in:

              app/uploaders/avatar_uploader.rb                          

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

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

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

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

CarrierWave gives you a store for permanent storage, and a enshroud for temporary storage. You tin use different stores, including filesystem and cloud storage.

About of the fourth dimension you are going to want to use CarrierWave together with an ORM. It is quite uncomplicated to mount uploaders on columns in your model, so you tin simply assign files and go going:

ActiveRecord

Make sure yous are loading CarrierWave after loading your ORM, otherwise you'll demand to crave the relevant extension manually, e.yard.:

              require              'carrierwave/orm/activerecord'            

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

              track g migration add_avatar_to_users avatar:string rail db:migrate                          

Open up your model file and mount the uploader:

              form              User              <              ApplicationRecord              mount_uploader              :avatar              ,              AvatarUploader              end            

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

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

Note: u.avatar will never render nada, even if at that place is no photo associated to information technology. To check if a photograph was saved to the model, use u.avatar.file.nil? instead.

DataMapper, Mongoid, Sequel

Other ORM support has been extracted into separate gems:

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

There are more than extensions listed in the wiki

Multiple file uploads

CarrierWave besides has user-friendly support for multiple file upload fields.

ActiveRecord

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

For databases with ActiveRecord json data type back up (eastward.g. PostgreSQL, MySQL)

              rails yard migration add_avatars_to_users avatars:json rails db:drift                          

For database without ActiveRecord json information blazon support (e.g. SQLite)

              rail g migration add_avatars_to_users avatars:string track db:migrate                          

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

Open your model file and mount the uploader:

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

Make sure that you mount the uploader with write (mount_uploaders) with due south not (mount_uploader) in order to avert errors when uploading multiple files

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

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

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

              params              .              require              (              :user              )              .              allow              (              :e-mail              ,              :first_name              ,              :last_name              ,              {              avatars:              [              ]              }              )            

Now y'all 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              .              new              (              params              [              :user              ]              )              u              .              save!              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 ane, y'all tin go like:

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

Sorting avatars is supported also by reordering hidden_field, an example using jQuery UI Sortable is available here.

Changing the storage directory

In social club 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'              stop              end            

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

If you lot store files outside the project root folder, you lot may desire to define cache_dir in the aforementioned mode:

              class              MyUploader              <              CarrierWave::Uploader::Base              def              cache_dir              '/tmp/projectname-cache'              end              terminate            

Securing uploads

Sure 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 yous're mounting the uploader, uploading a file with the incorrect extension will make the tape invalid instead. Otherwise, an error is raised.

              class              MyUploader              <              CarrierWave::Uploader::Base of operations              def              extension_allowlist              %w(              jpg              jpeg              gif              png              )              finish              stop            

The same matter could be washed using content types. Allow's say nosotros demand an uploader that accepts simply images. This can be done like this

              class              MyUploader              <              CarrierWave::Uploader::Base              def              content_type_allowlist              /epitome\//              end              end            

You can use a denylist to pass up content types. Let'southward say nosotros need an uploader that turn down JSON files. This can be done like this

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

CVE-2016-3714 (ImageTragick)

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

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

              course              MyUploader              <              CarrierWave::Uploader::Base              def              content_type_allowlist              [              /image\//              ]              stop              end            

Alarm: A content_type_allowlist is the only class of allowlist or denylist supported past CarrierWave that tin can effectively mitigate against CVE-2016-3714. Utilise of extension_allowlist will non inspect the file headers, and thus withal leaves your application open to the vulnerability.

Filenames and unicode chars

Another security effect you should care for is the file names (run across Ruby On Rails Security Guide). By default, CarrierWave provides only English letters, arabic numerals and some symbols as allowlisted characters in the file name. If you want to support local scripts (Cyrillic messages, letters with diacritics and and then on), you have to override sanitize_regexp method. Information technology should return regular expression which would friction match all non-allowed symbols.

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

Also make certain that allowing not-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 mime-types gem is a runtime dependency and the content type is fix automatically. Y'all no longer demand to do this manually.

Adding versions

Often you'll want to add different versions of the same file. The archetype instance is image thumbnails. There is congenital in back up for this*:

Note: You must have Imagemagick installed to practice prototype resizing.

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

To install Imagemagick on OSX with homebrew blazon the following:

              $ mash install imagemagick                          
              form              MyUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::MiniMagick              procedure              resize_to_fit:              [              800              ,              800              ]              version              :thumb              do              process              resize_to_fill:              [              200              ,              200              ]              stop              end            

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

A version called :thumb is so created, which is scaled to exactly 200 by 200 pixels. The thumbnail uses resize_to_fill which makes certain that the width and height specified are filled, only cropping if the aspect ratio requires it.

The above uploader could exist used similar this:

              uploader              =              AvatarUploader              .              new              uploader              .              shop!              (              my_file              )              # size: 1024x768              uploader              .              url              # => '/url/to/my_file.png'               # size: 800x800              uploader              .              thumb              .              url              # => '/url/to/thumb_my_file.png'   # size: 200x200            

I of import thing to remember is that process is called before versions are created. This can cutting 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 inside the specified dimensions while retaining the original attribute ratio. Will only resize the image if it is larger than the specified dimensions. The resulting prototype may exist shorter or narrower than specified in the smaller dimension simply 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 only will non exist larger than the specified values.
  • resize_to_fill - Resize the epitome to fit within the specified dimensions while retaining the aspect ratio of the original prototype. If necessary, crop the image in the larger dimension. Optionally, a "gravity" may be specified, for instance "Middle", or "NorthEast".
  • resize_and_pad - Resize the image to fit inside the specified dimensions while retaining the original aspect ratio. If necessary, will pad the remaining expanse with the given color, which defaults to transparent (for gif and png, white for jpeg). Optionally, a "gravity" may exist specified, as in a higher place.

See carrierwave/processing/mini_magick.rb for details.

conditional process

If you lot want to use conditional procedure, you tin only use if statement.

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

              course              MyUploader              <              CarrierWave::Uploader::Base of operations              process              :calibration              =>              [              200              ,              200              ]              ,              :if              =>              :prototype?              def              paradigm?              (              carrier_wave_sanitized_file              )              true              end              stop            

Nested versions

It is possible to nest versions within versions:

              class              MyUploader              <              CarrierWave::Uploader::Base of operations              version              :animal              do              version              :human              version              :monkey              version              :llama              end              cease            

Provisional versions

Occasionally you want to restrict the creation of versions on certain properties inside the model or based on the motion-picture show itself.

              class              MyUploader              <              CarrierWave::Uploader::Base              version              :human              ,              if:              :is_human?              version              :monkey              ,              if:              :is_monkey?              version              :banner              ,              if:              :is_landscape?              individual              def              is_human?              picture              model              .              can_program?              (              :ruddy              )              end              def              is_monkey?              pic              model              .              favorite_food              ==              'banana'              stop              def              is_landscape?              picture              image              =              MiniMagick::Image              .              new              (              picture              .              path              )              image              [              :width              ]              >              image              [              :height              ]              end              end            

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

Create versions from existing versions

For performance reasons, it is oftentimes 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 paradigm.

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

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

Making uploads work across form redisplays

Often you'll observe that uploaded files disappear when a validation fails. CarrierWave has a characteristic that makes it easy to remember the uploaded file even in that case. Suppose your user model has an uploader mounted on avatar file, but add a hidden field called avatar_cache (don't forget to add information technology to the attr_accessible listing as necessary). In Track, this would look like this:

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

It might be a good idea 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 } practise |f|              %>                                                                                                                                                                              <              p              >              <              label              >My Avatar</              label              >              <%=              image_tag              (              @user              .              avatar_url              )              if              @user              .              avatar?              %>                                            <%=              f              .              file_field              :avatar              %>                                            <%=              f              .              hidden_field              :avatar_cache              %>              </              p              >              <%              finish              %>            

Removing uploaded files

If you want to remove a previously uploaded file on a mounted uploader, y'all can hands add together a checkbox to the form which will remove the file when checked.

              <%=              form_for @user, html: { multipart: true } do |f|              %>                                                                                                                                                                              <              p              >              <              label              >My Avatar</              characterization              >              <%=              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 you want to remove the file manually, yous tin can telephone call remove_avatar!, and then save the object.

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

Uploading files from a remote location

Your users may notice information technology 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 course and you're good to become:

              <%=              form_for @user, html: { multipart: truthful } practise |f|              %>                                                                                                                                                                              <              p              >              <              label              >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 point invalid URLs and download failures automatically with attribute validation errors. If you aren't, or you disable CarrierWave's validate_download option, you'll need to handle those errors yourself.

Retry option for download from remote location

If y'all want to retry the download from the Remote URL, enable the download_retry_count option, an error occurs during download, information technology will try to execute the specified number of times every 5 2d. This option is effective when the remote destination is unstable.

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

Providing a default URL

In many cases, specially when working with images, it might exist a good thought to provide a default url, a fallback in instance no file has been uploaded. You lot can practise this easily by overriding the default_url method in your uploader:

              class              MyUploader              <              CarrierWave::Uploader::Base              def              default_url              (*args              )              "/images/fallback/"              +              [              version_name              ,              "default.png"              ]              .              meaty              .              join              (              '_'              )              cease              finish            

Or if yous are using the Rail nugget pipeline:

              class              MyUploader              <              CarrierWave::Uploader::Base              def              default_url              (*args              )              ActionController::Base              .              helpers              .              asset_path              (              "fallback/"              +              [              version_name              ,              "default.png"              ]              .              meaty              .              join              (              '_'              )              )              end              end            

Recreating versions

You might come to a state of affairs where you want to retroactively change a version or add a new one. Y'all can use the recreate_versions! method to recreate the versions from the base file. This uses a naive arroyo which will re-upload and procedure the specified version or all versions, if none is passed equally an argument.

When y'all are generating random unique filenames you have to phone call save! on the model after using recreate_versions!. This is necessary because recreate_versions! doesn't save the new filename to the database. Calling save! yourself will prevent that the database and file system are running out of sync.

              case              =              MyUploader              .              new              instance              .              recreate_versions!              (              :pollex              ,              :big              )            

Or on a mounted uploader:

              User              .              find_each              do              |user|              user              .              avatar              .              recreate_versions!              end            

Note: recreate_versions! will throw an exception on records without an image. To avert this, telescopic the records to those with images or check if an image exists inside the cake. 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 lot tin configure, both globally and on a per-uploader ground:

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

Or alternatively:

              class              AvatarUploader              <              CarrierWave::Uploader::Base of operations              permissions              0777              finish            

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

              config/initializers/carrierwave.rb                          

If you desire CarrierWave to fail noisily in development, you lot can alter these configs in your environment file:

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

Testing with CarrierWave

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

              if              Rails              .              env              .              test?              or              Rails              .              env              .              cucumber?              CarrierWave              .              configure              practice              |config|              config              .              storage              =              :file              config              .              enable_processing              =              imitation              end              end            

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

If you need to examination your processing, you should test it in isolation, and enable processing simply for those tests that need information technology.

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

              require              'carrierwave/test/matchers'              describe              MyUploader              exercise              include              CarrierWave::Test::Matchers              let              (              :user              )              {              double              (              'user'              )              }              let              (              :uploader              )              {              MyUploader              .              new              (              user              ,              :avatar              )              }              earlier              do              MyUploader              .              enable_processing              =              true              File              .              open up              (              path_to_file              )              {              |f|              uploader              .              store!              (              f              )              }              end              after              do              MyUploader              .              enable_processing              =              false              uploader              .              remove!              finish              context              'the thumb version'              do              information technology              "scales downwardly a landscape image to exist exactly 64 past 64 pixels"              do              expect              (              uploader              .              pollex              )              .              to              have_dimensions              (              64              ,              64              )              end              finish              context              'the small-scale version'              do              information technology              "scales downwardly a landscape epitome to fit inside 200 by 200 pixels"              do              wait              (              uploader              .              small              )              .              to              be_no_larger_than              (              200              ,              200              )              end              end              it              "makes the image readable simply to the owner and not executable"              practise              expect              (              uploader              )              .              to              have_permissions              (              0600              )              stop              it              "has the correct format"              do              expect              (              uploader              )              .              to              be_format              (              'png'              )              end              stop            

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

Setting the enable_processing flag on an uploader volition prevent any of the versions from processing likewise. Processing tin can be enabled for a single version by setting the processing flag on the version like and so:

              @uploader              .              thumb              .              enable_processing              =              true            

Fog

If you want to use fog you must add in your CarrierWave initializer the post-obit lines

              config              .              fog_credentials              =              {              ...              }              # Provider specific credentials            

Using Amazon S3

Fog AWS is used to support Amazon S3. Ensure y'all take it in your Gemfile:

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

              CarrierWave              .              configure              practise              |config|              config              .              fog_credentials              =              {              provider:              'AWS'              ,              # required              aws_access_key_id:              '30'              ,              # 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 'the states-due east-1'              host:              's3.example.com'              ,              # optional, defaults to nil              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 just does not demand caches persisted across requests,              # uncomment the line :file instead of the default :storage.  Otherwise, it will apply AWS as the temp enshroud store.              # config.cache_storage = :file              terminate            

In your uploader, set the storage to :fog

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

That'due south it! Y'all tin can still employ the CarrierWave::Uploader#url method to return the url to the file on Amazon S3.

Annotation: for Carrierwave to work properly information technology needs credentials with the post-obit permissions:

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

Using Rackspace Cloud Files

Fog is used to back up Rackspace Cloud Files. Ensure you have information technology in your Gemfile:

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

Using a United states-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            

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

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

In your uploader, set the storage to :fog

              grade              AvatarUploader              <              CarrierWave::Uploader::Base of operations              storage              :fog              finish            

That'due south information technology! You can yet utilise the CarrierWave::Uploader#url method to render the url to the file on Rackspace Deject Files.

Using Google Cloud Storage

Fog is used to support Google Deject Storage. Ensure yous have it in your Gemfile:

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

Please read the fog-google README on how to become 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'              terminate            

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, set the storage to :fog

              course              AvatarUploader              <              CarrierWave::Uploader::Base of operations              storage              :fog              end            

That's it! Yous tin 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 employ, information technology will just load the entire library (unless you lot use e.thousand. [fog-aws, fog-google] instead of fog proper). If you adopt to load fewer classes into your application, you need to load those parts of Fog yourself before loading CarrierWave in your Gemfile. Ex:

              jewel              "fog"              ,              "~> 1.27"              ,              require:              "fog/rackspace/storage"              precious stone              "carrierwave"            

A couple of notes nigh versions:

  • This functionality was introduced in Fog v1.xx.
  • This functionality is slated for CarrierWave v1.0.0.

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

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

Beware that this specific require is only needed when working with a fog provider that was non extracted to its ain precious stone nonetheless. A listing of the extracted providers can be found in the page of the fog organizations here.

When in dubiety, inspect Fog.constants to meet what has been loaded.

Dynamic Asset Host

The asset_host config property can be assigned a proc (or anything that responds to phone call) for generating the host dynamically. The proc-compliant object gets an instance of the current CarrierWave::Storage::Fog::File or CarrierWave::SanitizedFile as its only statement.

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

Using RMagick

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

              grade              AvatarUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::RMagick              cease            

The RMagick module gives you a few methods, like CarrierWave::RMagick#resize_to_fill which manipulate the image file in some fashion. You tin prepare a process callback, which will call that method any fourth dimension a file is uploaded. There is a sit-in of convert hither. 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            

Cheque 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 accept the power of ImageMagick without having to worry most installing all the RMagick libraries.

See the MiniMagick site for more details:

https://github.com/minimagick/minimagick

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

http://www.imagemagick.org/script/control-line-options.php

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

              class              AvatarUploader              <              CarrierWave::Uploader::Base of operations              include              CarrierWave::MiniMagick              process              resize_to_fill:              [              200              ,              200              ]              terminate            

Migrating from Paperclip

If you are using Paperclip, y'all tin use the provided compatibility module:

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

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

Be sure to utilise mount_on to specify the correct cavalcade:

              mount_uploader              :avatar              ,              AvatarUploader              ,              mount_on:              :avatar_file_name            

I18n

The Active Record validations employ the Runway i18n framework. Add together these keys to your translations file:

              errors:              messages:              carrierwave_processing_error:              failed to be processed              carrierwave_integrity_error:              is non of an allowed file type              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 not allowed to upload %{extension} files, prohibited types: %{prohibited_types}"                            content_type_allowlist_error:                              "You lot are not allowed to upload %{content_type} files, allowed types: %{allowed_types}"                            content_type_denylist_error:                              "You are not immune to upload %{content_type} files"                            processing_error:                              "Failed to dispense, maybe information technology is non an paradigm?"                            min_size_error:                              "File size should exist greater than %{min_size}"                            max_size_error:                              "File size should be less than %{max_size}"                          

The carrierwave-i18n library 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 big files, this can exist prohibitively time consuming.

You lot may change 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              terminate            

When the move_to_cache and/or move_to_store methods return truthful, 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

Past default, mounting an uploader into an ActiveRecord model volition add a few callbacks. For case, this code:

              course              User              mount_uploader              :avatar              ,              AvatarUploader              terminate            

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 afterward uploading a new one), yous can apply ActiveRecord'south skip_callback method.

              grade              User              mount_uploader              :avatar              ,              AvatarUploader              skip_callback              :commit              ,              :later on              ,              :remove_previously_stored_avatar              cease            

Uploader Callbacks

In improver to the ActiveRecord callbacks described in a higher place, uploaders besides take callbacks.

              class              MyUploader              < ::CarrierWave::Uploader::Base              earlier              :remove              ,              :log_removal              individual              def              log_removal              ::Track              .              logger              .              info              (              format              (              'Deleting file on S3: %southward'              ,              @file              )              )              end              end            

Uploader callbacks can exist before or later the following events:

              cache procedure remove retrieve_from_cache store                          

Contributing to CarrierWave

Run across CONTRIBUTING.md

License

The MIT License (MIT)

Copyright (c) 2008-2015 Jonas Nicklas

Permission is hereby granted, gratuitous of charge, to whatever 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 utilize, copy, change, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to let persons to whom the Software is furnished to practise so, subject to the post-obit conditions:

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

THE SOFTWARE IS PROVIDED "Equally IS", WITHOUT WARRANTY OF Any KIND, EXPRESS OR Unsaid, INCLUDING Simply Not Express TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A Item PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR Whatever 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 Utilize OR OTHER DEALINGS IN THE SOFTWARE.

rollinspondne1949.blogspot.com

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

0 Response to "Carrierwave Ruby Mount Uploader to Existing Modal"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel