process uploaded file before sending to carrierwave uploader

CarrierWave

This gem provides a uncomplicated and extremely flexible way to upload files from Ruby-red applications. Information technology works well with Rack based spider web applications, such equally Carmine on Rails.

Build Status Code Climate SemVer

Information

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

Getting Help

  • Delight ask the customs on Stack Overflow for assistance if you take any questions. Delight do non post usage questions on the issue tracker.
  • Please report bugs on the issue tracker just read the "getting help" section in the wiki offset.

Installation

Install the latest release:

              $ precious stone install carrierwave                          

In Runway, add together it to your Gemfile:

              gem              'carrierwave'              ,              '~> 2.0'            

Finally, restart the server to apply the changes.

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

Getting Started

Start off past generating an uploader:

              rails generate uploader Avatar                          

this should give you a file in:

              app/uploaders/avatar_uploader.rb                          

Cheque out this file for some hints on how you can customize your uploader. Information technology should look something similar this:

              form              AvatarUploader              <              CarrierWave::Uploader::Base              storage              :file              stop            

Y'all tin employ your uploader class to store and remember files like 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 utilize different stores, including filesystem and cloud storage.

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

ActiveRecord

Make sure you are loading CarrierWave afterward loading your ORM, otherwise you'll need to crave the relevant extension manually, due east.thousand.:

              require              'carrierwave/orm/activerecord'            

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

              rails g migration add_avatar_to_users avatar:string rails db:drift                          

Open your model file and mount the uploader:

              class              User              <              ApplicationRecord              mount_uploader              :avatar              ,              AvatarUploader              end            

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

              u              =              User              .              new              u              .              avatar              =              params              [              :file              ]              # Assign a file like this, or              # like this              File              .              open up              (              'somewhere'              )              do              |f|              u              .              avatar              =              f              stop              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 volition never return cypher, even if in that location is no photo associated to it. To cheque if a photograph was saved to the model, utilize u.avatar.file.nil? instead.

DataMapper, Mongoid, Sequel

Other ORM support has been extracted into divide gems:

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

There are more than extensions listed in the wiki

Multiple file uploads

CarrierWave besides has convenient 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 instance, 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:migrate                          

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

              rail g migration add_avatars_to_users avatars:string rails db:migrate                          

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

Open your model file and mount the uploader:

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

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

Brand certain your file input fields are gear up as multiple file fields. For example in Rails yous'll want to practice something similar this:

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

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

              params              .              require              (              :user              )              .              permit              (              :email              ,              :first_name              ,              :last_name              ,              {              avatars:              [              ]              }              )            

Now y'all tin select multiple files in the upload dialog (due east.g. SHIFT+SELECT), and they volition automatically be stored when the record is saved.

              u              =              User              .              new              (              params              [              :user              ]              )              u              .              salvage!              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 1, you lot can go similar:

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

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

Changing the storage directory

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

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

This works for the file storage likewise as Amazon S3 and Rackspace Cloud Files. Define store_dir as goose egg if y'all'd like to store files at the root level.

If you store files exterior the project root folder, you may want to define cache_dir in the same way:

              course              MyUploader              <              CarrierWave::Uploader::Base              def              cache_dir              '/tmp/projectname-cache'              stop              end            

Securing uploads

Certain files might exist unsafe if uploaded to the incorrect 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 brand the record invalid instead. Otherwise, an fault is raised.

              grade              MyUploader              <              CarrierWave::Uploader::Base              def              extension_allowlist              %w(              jpg              jpeg              gif              png              )              end              terminate            

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

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

Yous tin use a denylist to reject content types. Let'south say we need an uploader that decline JSON files. This can be washed like this

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

CVE-2016-3714 (ImageTragick)

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

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

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

Alert: A content_type_allowlist is the only form of allowlist or denylist supported by CarrierWave that can finer mitigate against CVE-2016-3714. Apply of extension_allowlist volition non audit the file headers, and thus yet leaves your application open to the vulnerability.

Filenames and unicode chars

Another security event you should care for is the file names (meet Cerise On Runway Security Guide). By default, CarrierWave provides only English messages, 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 so on), you lot have to override sanitize_regexp method. It should return regular expression which would lucifer all non-allowed symbols.

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

Also make sure that assuasive non-latin characters won't cause a compatibility result with a 3rd-party plugins or client-side software.

Setting the content type

Every bit of v0.11.0, the mime-types gem is a runtime dependency and the content type is gear up automatically. You no longer need to do this manually.

Adding versions

Frequently y'all'll want to add together different versions of the same file. The classic example is prototype thumbnails. There is built in support for this*:

Annotation: You lot must have Imagemagick installed to exercise image 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                          
              class              MyUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::MiniMagick              process              resize_to_fit:              [              800              ,              800              ]              version              :thumb              do              process              resize_to_fill:              [              200              ,              200              ]              end              end            

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

A version called :pollex is and 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 information technology.

The above uploader could exist used like 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            

One of import thing to remember is that procedure is called before versions are created. This can cut down on processing cost.

Processing Methods: mini_magick

  • convert - Changes the image encoding format to the given format, eg. jpg
  • resize_to_limit - Resize the image to fit within the specified dimensions while retaining the original aspect ratio. Volition simply resize the prototype if it is larger than the specified dimensions. The resulting prototype may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.
  • resize_to_fit - Resize the paradigm 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 but volition not be larger than the specified values.
  • resize_to_fill - Resize the image to fit within the specified dimensions while retaining the aspect ratio of the original image. If necessary, crop the image in the larger dimension. Optionally, a "gravity" may be specified, for example "Center", or "NorthEast".
  • resize_and_pad - Resize the image to fit inside the specified dimensions while retaining the original aspect ratio. If necessary, will pad the remaining area with the given color, which defaults to transparent (for gif and png, white for jpeg). Optionally, a "gravity" may be specified, equally higher up.

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

conditional procedure

If yous want to use conditional process, y'all tin merely use if statement.

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

              class              MyUploader              <              CarrierWave::Uploader::Base              process              :calibration              =>              [              200              ,              200              ]              ,              :if              =>              :image?              def              image?              (              carrier_wave_sanitized_file              )              true              cease              end            

Nested versions

Information technology is possible to nest versions within versions:

              class              MyUploader              <              CarrierWave::Uploader::Base              version              :fauna              practise              version              :human being              version              :monkey              version              :llama              end              terminate            

Conditional versions

Occasionally you desire to restrict the creation of versions on certain properties inside the model or based on the movie itself.

              class              MyUploader              <              CarrierWave::Uploader::Base              version              :man              ,              if:              :is_human?              version              :monkey              ,              if:              :is_monkey?              version              :banner              ,              if:              :is_landscape?              private              def              is_human?              moving picture              model              .              can_program?              (              :ruby              )              end              def              is_monkey?              movie              model              .              favorite_food              ==              'banana'              end              def              is_landscape?              picture show              prototype              =              MiniMagick::Image              .              new              (              motion-picture show              .              path              )              image              [              :width              ]              >              image              [              :height              ]              cease              end            

The model variable points to the case object the uploader is fastened to.

Create versions from existing versions

For performance 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 side by side is smaller than the terminal, information technology volition take less time to generate from a smaller, already processed image.

              course              MyUploader              <              CarrierWave::Uploader::Base of operations              version              :thumb              do              process              resize_to_fill:              [              280              ,              280              ]              end              version              :small_thumb              ,              from_version:              :pollex              do              process              resize_to_fill:              [              20              ,              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 across course redisplays

Often yous'll notice that uploaded files disappear when a validation fails. CarrierWave has a feature that makes information technology easy to recollect the uploaded file even in that case. Suppose your user model has an uploader mounted on avatar file, just add a hidden field called avatar_cache (don't forget to add it to the attr_accessible list as necessary). In Runway, this would look like this:

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

It might be a good idea to show the user that a file has been uploaded, in the case of images, a small thumbnail would exist 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 desire to remove a previously uploaded file on a mounted uploader, y'all tin 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 yous want to remove the file manually, you lot can call remove_avatar!, then save the object.

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

Uploading files from a remote location

Your users may discover information technology convenient to upload a file from a location on the Internet via a URL. CarrierWave makes this elementary, just add the appropriate aspect to your form and yous're practiced to become:

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

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

Retry pick for download from remote location

If you desire to retry the download from the Remote URL, enable the download_retry_count selection, an error occurs during download, it will endeavor to execute the specified number of times every 5 second. This option is effective when the remote destination is unstable.

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

Providing a default URL

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

              course              MyUploader              <              CarrierWave::Uploader::Base              def              default_url              (*args              )              "/images/fallback/"              +              [              version_name              ,              "default.png"              ]              .              compact              .              join              (              '_'              )              end              end            

Or if you lot 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"              ]              .              compact              .              bring together              (              '_'              )              )              end              end            

Recreating versions

You might come to a situation where you lot want to retroactively change a version or add together a new 1. You 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 as an argument.

When you are generating random unique filenames yous have to 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 forestall that the database and file organisation are running out of sync.

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

Or on a mounted uploader:

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

Note: recreate_versions! volition throw an exception on records without an prototype. To avoid this, scope the records to those with images or check if an epitome exists within the cake. If y'all're using ActiveRecord, recreating versions for a user avatar might look like this:

              User              .              find_each              practice              |user|              user              .              avatar              .              recreate_versions!              if              user              .              avatar?              end            

Configuring CarrierWave

CarrierWave has a broad range of configuration options, which y'all can configure, both globally and on a per-uploader ground:

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

Or alternatively:

              course              AvatarUploader              <              CarrierWave::Uploader::Base of operations              permissions              0777              end            

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

              config/initializers/carrierwave.rb                          

If you desire CarrierWave to neglect noisily in development, y'all can alter these configs in your environment file:

              CarrierWave              .              configure              do              |config|              config              .              ignore_integrity_errors              =              false              config              .              ignore_processing_errors              =              imitation              config              .              ignore_download_errors              =              faux              cease            

Testing with CarrierWave

Information technology'due south a good idea to test your uploaders in isolation. In order to speed up your tests, it's recommended to switch off processing in your tests, and to utilise the file storage. In Rails y'all could practise that by adding an initializer with:

              if              Rails              .              env              .              examination?              or              Track              .              env              .              cucumber?              CarrierWave              .              configure              do              |config|              config              .              storage              =              :file              config              .              enable_processing              =              faux              end              terminate            

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

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

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

              require              'carrierwave/test/matchers'              describe              MyUploader              practice              include              CarrierWave::Test::Matchers              let              (              :user              )              {              double              (              'user'              )              }              let              (              :uploader              )              {              MyUploader              .              new              (              user              ,              :avatar              )              }              earlier              do              MyUploader              .              enable_processing              =              true              File              .              open              (              path_to_file              )              {              |f|              uploader              .              store!              (              f              )              }              end              subsequently              do              MyUploader              .              enable_processing              =              faux              uploader              .              remove!              end              context              'the pollex version'              do              information technology              "scales down a landscape image to be exactly 64 by 64 pixels"              do              expect              (              uploader              .              thumb              )              .              to              have_dimensions              (              64              ,              64              )              end              end              context              'the small version'              do              it              "scales downwardly a mural paradigm to fit within 200 past 200 pixels"              exercise              expect              (              uploader              .              small-scale              )              .              to              be_no_larger_than              (              200              ,              200              )              finish              stop              information technology              "makes the image readable only to the owner and non executable"              practice              expect              (              uploader              )              .              to              have_permissions              (              0600              )              terminate              it              "has the correct format"              do              look              (              uploader              )              .              to              be_format              (              'png'              )              end              end            

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

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

              @uploader              .              thumb              .              enable_processing              =              true            

Fog

If yous want to use fog you 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 lot accept it in your Gemfile:

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

              CarrierWave              .              configure              do              |config|              config              .              fog_credentials              =              {              provider:              'AWS'              ,              # required              aws_access_key_id:              'xxx'              ,              # required unless using use_iam_profile              aws_secret_access_key:              'yyy'              ,              # required unless using use_iam_profile              use_iam_profile:              true              ,              # optional, defaults to false              region:              'european union-due west-ane'              ,              # optional, defaults to 'us-e-1'              host:              's3.example.com'              ,              # optional, defaults to naught              endpoint:              'https://s3.example.com:8080'              # optional, defaults to cypher              }              config              .              fog_directory              =              'name_of_bucket'              # required              config              .              fog_public              =              false              # optional, defaults to true              config              .              fog_attributes              =              {              cache_control:              "public, max-age=                  #{                  365                  .                  days                  .                  to_i                  }                "              }              # optional, defaults to {}              # For an awarding which utilizes multiple servers but does not demand caches persisted across requests,              # uncomment the line :file instead of the default :storage.  Otherwise, it will apply AWS as the temp cache store.              # config.cache_storage = :file              end            

In your uploader, fix the storage to :fog

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

That'southward information technology! You lot can still use the CarrierWave::Uploader#url method to return the url to the file on Amazon S3.

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

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

Using Rackspace Cloud Files

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

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

Using a U.s.-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'              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'              cease            

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

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

In your uploader, set the storage to :fog

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

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

Using Google Deject Storage

Fog is used to support Google Cloud Storage. Ensure you have information technology 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 causeless that the directory already exists, so delight create it if need 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'              stop            

In your uploader, set the storage to :fog

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

That's it! Yous can still utilize 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 use, it will just load the unabridged library (unless y'all use e.m. [fog-aws, fog-google] instead of fog proper). If you prefer to load fewer classes into your awarding, yous need to load those parts of Fog yourself before loading CarrierWave in your Gemfile. Ex:

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

A couple of notes about versions:

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

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

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

Beware that this specific crave is only needed when working with a fog provider that was non extracted to its own gem withal. A listing of the extracted providers tin be constitute in the page of the fog organizations here.

When in doubtfulness, inspect Fog.constants to see what has been loaded.

Dynamic Asset Host

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

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

Using RMagick

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

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

The RMagick module gives you a few methods, like CarrierWave::RMagick#resize_to_fill which manipulate the image file in some way. Yous tin can set a process callback, which volition phone call that method any fourth dimension a file is uploaded. At that place is a demonstration of convert here. Catechumen will simply work if the file has the aforementioned file extension, thus the use of the filename method.

              course              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?              finish              end            

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

Using MiniMagick

MiniMagick is similar to RMagick but performs all the operations using the 'catechumen' CLI which is function of the standard ImageMagick kit. This allows y'all to have the ability 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 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 as for the RMagick processor.

              class              AvatarUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::MiniMagick              process              resize_to_fill:              [              200              ,              200              ]              finish            

Migrating from Paperclip

If you lot are using Paperclip, you tin can utilise the provided compatibility module:

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

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

Be certain to use mount_on to specify the correct column:

              mount_uploader              :avatar              ,              AvatarUploader              ,              mount_on:              :avatar_file_name            

I18n

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

              errors:              messages:              carrierwave_processing_error:              failed to be processed              carrierwave_integrity_error:              is not of an allowed file type              carrierwave_download_error:              could not be downloaded              extension_allowlist_error:                              "You are not immune 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, allowed types: %{allowed_types}"                            content_type_denylist_error:                              "You are not allowed to upload %{content_type} files"                            processing_error:                              "Failed to manipulate, maybe information technology 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.

Large files

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

You lot may change this behavior 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              end              def              move_to_store              true              terminate              end            

When the move_to_cache and/or move_to_store methods render truthful, files will be moved (instead of copied) to the cache 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 a few callbacks. For example, this code:

              class              User              mount_uploader              :avatar              ,              AvatarUploader              end            

Will add these callbacks:

              before_save              :write_avatar_identifier              after_save              :store_previous_changes_for_avatar              after_commit              :remove_avatar!              ,              on:              :destroy              after_commit              :mark_remove_avatar_false              ,              on:              :update              after_commit              :remove_previously_stored_avatar              ,              on:              :update              after_commit              :store_avatar!              ,              on:              [              :create              ,              :update              ]            

If you lot want to skip any of these callbacks (eg. you want to proceed the existing avatar, fifty-fifty after uploading a new one), you tin can utilise ActiveRecord's skip_callback method.

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

Uploader Callbacks

In addition to the ActiveRecord callbacks described to a higher place, uploaders besides have callbacks.

              course              MyUploader              < ::CarrierWave::Uploader::Base              before              :remove              ,              :log_removal              private              def              log_removal              ::Rails              .              logger              .              info              (              format              (              'Deleting file on S3: %s'              ,              @file              )              )              end              end            

Uploader callbacks can be before or after the following events:

              cache process remove retrieve_from_cache shop                          

Contributing to CarrierWave

Run across CONTRIBUTING.dr.

License

The MIT License (MIT)

Copyright (c) 2008-2015 Jonas Nicklas

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Unsaid, INCLUDING Only NOT Limited TO THE WARRANTIES OF MERCHANTABILITY, Fitness FOR A Particular PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS Be 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.

muellerraingerred.blogspot.com

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

0 Response to "process uploaded file before sending to carrierwave uploader"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel