Skip to content Skip to sidebar Skip to footer

Awss3errorsaccessdenied When Uploading the Image Rails Carrier Wave

CarrierWave

This gem provides a uncomplicated and extremely flexible way to upload files from Reddish applications. It works well with Rack based web applications, such every bit Cherry on Rails.

Build Status Code Climate SemVer

Information

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

Getting Help

  • Please inquire the community on Stack Overflow for help if you have whatever questions. Please exercise not mail service usage questions on the issue tracker.
  • Please written report bugs on the upshot tracker merely read the "getting help" section in the wiki get-go.

Installation

Install the latest release:

              $ jewel install carrierwave                          

In Rails, add information technology to your Gemfile:

              jewel              'carrierwave'              ,              '~> 2.0'            

Finally, restart the server to apply the changes.

Equally of version 2.0, CarrierWave requires Rails v.0 or higher and Ruby 2.two or college. If you're on Rails four, you should use 1.x.

Getting Started

Offset 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 you tin can customize your uploader. It should look something like this:

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

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

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

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

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

ActiveRecord

Make sure you are loading CarrierWave subsequently loading your ORM, otherwise you'll need to require the relevant extension manually, due east.k.:

              require              'carrierwave/orm/activerecord'            

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

              runway g migration add_avatar_to_users avatar:string rails db:drift                          

Open your model file and mountain the uploader:

              course              User              <              ApplicationRecord              mount_uploader              :avatar              ,              AvatarUploader              cease            

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

              u              =              User              .              new              u              .              avatar              =              params              [              :file              ]              # Assign a file like this, or              # similar this              File              .              open              (              'somewhere'              )              do              |f|              u              .              avatar              =              f              end              u              .              relieve!              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 return aught, fifty-fifty if in that location is no photograph associated to it. To check if a photo was saved to the model, utilize 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 extensions listed in the wiki

Multiple file uploads

CarrierWave likewise has convenient back up for multiple file upload fields.

ActiveRecord

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

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

              rails g migration add_avatars_to_users avatars:json rails db:migrate                          

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

              runway g migration add_avatars_to_users avatars:string rails db:migrate                          

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

Open your model file and mount the uploader:

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

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

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

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

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

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

At present you lot tin select multiple files in the upload dialog (e.m. SHIFT+SELECT), and they will automatically be stored when the tape 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 yous want to preserve existing files on uploading new one, you tin can become like:

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

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

Changing the storage directory

In social club to modify where uploaded files are put, just override the store_dir method:

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

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

If yous store files exterior the project root folder, you may want to ascertain cache_dir in the same style:

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

Securing uploads

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

If you're mounting the uploader, uploading a file with the wrong extension will brand the tape invalid instead. Otherwise, an mistake is raised.

              form              MyUploader              <              CarrierWave::Uploader::Base of operations              def              extension_allowlist              %westward(              jpg              jpeg              gif              png              )              end              end            

The same thing could exist done using content types. Let'south say we need an uploader that accepts just images. This tin can exist washed like this

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

You tin utilize a denylist to reject content types. Let'southward say we need an uploader that refuse JSON files. This can exist done similar this

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

CVE-2016-3714 (ImageTragick)

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

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

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

WARNING: A content_type_allowlist is the only grade of allowlist or denylist supported by CarrierWave that can finer mitigate against CVE-2016-3714. Utilise of extension_allowlist will non inspect the file headers, and thus still leaves your application open up to the vulnerability.

Filenames and unicode chars

Another security effect you should intendance for is the file names (meet Reddish On Rails Security Guide). By default, CarrierWave provides but English language letters, arabic numerals and some symbols as allowlisted characters in the file name. If you want to support local scripts (Cyrillic letters, messages with diacritics and so on), you lot take to override sanitize_regexp method. It should return regular expression which would lucifer all non-allowed symbols.

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

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

Setting the content blazon

Equally of v0.11.0, the mime-types gem is a runtime dependency and the content type is set up automatically. Yous no longer need to do this manually.

Adding versions

Frequently y'all'll desire to add different versions of the same file. The classic instance is image thumbnails. There is built in support for this*:

Notation: You must take Imagemagick installed to do paradigm resizing.

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

To install Imagemagick on OSX with homebrew type the following:

              $ brew install imagemagick                          
              grade              MyUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::MiniMagick              process              resize_to_fit:              [              800              ,              800              ]              version              :thumb              do              process              resize_to_fill:              [              200              ,              200              ]              end              end            

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

A version called :thumb is then created, which is scaled to exactly 200 by 200 pixels. The thumbnail uses resize_to_fill which makes sure that the width and meridian specified are filled, just 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            

1 important matter to remember is that process is called before versions are created. This can cutting down on processing toll.

Processing Methods: mini_magick

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

See carrierwave/processing/mini_magick.rb for details.

conditional process

If you want to use conditional process, you can but use if statement.

See carrierwave/uploader/processing.rb for details.

              course              MyUploader              <              CarrierWave::Uploader::Base              process              :scale              =>              [              200              ,              200              ]              ,              :if              =>              :image?              def              image?              (              carrier_wave_sanitized_file              )              truthful              finish              end            

Nested versions

It is possible to nest versions within versions:

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

Conditional versions

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

              class              MyUploader              <              CarrierWave::Uploader::Base of operations              version              :man              ,              if:              :is_human?              version              :monkey              ,              if:              :is_monkey?              version              :imprint              ,              if:              :is_landscape?              private              def              is_human?              picture              model              .              can_program?              (              :ruby              )              end              def              is_monkey?              picture              model              .              favorite_food              ==              'banana'              cease              def              is_landscape?              film              prototype              =              MiniMagick::Image              .              new              (              picture              .              path              )              image              [              :width              ]              >              epitome              [              :acme              ]              terminate              end            

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

Create versions from existing versions

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

              course              MyUploader              <              CarrierWave::Uploader::Base of operations              version              :pollex              do              process              resize_to_fill:              [              280              ,              280              ]              end              version              :small_thumb              ,              from_version:              :pollex              do              process              resize_to_fill:              [              20              ,              20              ]              end              stop            

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

Making uploads work beyond class redisplays

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

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

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

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

Removing uploaded files

If y'all desire to remove a previously uploaded file on a mounted uploader, you tin easily add a checkbox to the class which will remove the file when checked.

              <%=              form_for @user, html: { multipart: true } do |f|              %>                                                                                                                                                                              <              p              >              <              characterization              >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              </              characterization              >              </              p              >              <%              end              %>            

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

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

Uploading files from a remote location

Your users may find information technology convenient to upload a file from a location on the Internet via a URL. CarrierWave makes this uncomplicated, but add together the advisable attribute to your form and y'all're skilful to get:

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

If yous're using ActiveRecord, CarrierWave will indicate invalid URLs and download failures automatically with attribute validation errors. If you aren't, or you disable CarrierWave's validate_download choice, yous'll need to handle those errors yourself.

Retry pick for download from remote location

If you want to retry the download from the Remote URL, enable the download_retry_count option, an mistake occurs during download, it 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              =              three              # Default 0              cease            

Providing a default URL

In many cases, especially when working with images, information technology might be a good idea to provide a default url, a fallback in case no file has been uploaded. You lot can do this easily past overriding the default_url method in your uploader:

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

Or if y'all are using the Rails asset pipeline:

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

Recreating versions

Yous might come to a situation where you desire to retroactively change a version or add together a new one. You can use the recreate_versions! method to recreate the versions from the base of operations file. This uses a naive approach which will re-upload and procedure the specified version or all versions, if none is passed equally an argument.

When you are generating random unique filenames y'all accept to telephone 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 volition prevent that the database and file organisation are running out of sync.

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

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, scope the records to those with images or check if an image exists within the cake. If you're using ActiveRecord, recreating versions for a user avatar might look similar this:

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

Configuring CarrierWave

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

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

Or alternatively:

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

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

              config/initializers/carrierwave.rb                          

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

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

Testing with CarrierWave

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

              if              Rails              .              env              .              test?              or              Rails              .              env              .              cucumber?              CarrierWave              .              configure              do              |config|              config              .              storage              =              :file              config              .              enable_processing              =              fake              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 test your processing, you should examination it in isolation, and enable processing only for those tests that need it.

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

              crave              'carrierwave/test/matchers'              describe              MyUploader              do              include              CarrierWave::Test::Matchers              let              (              :user              )              {              double              (              'user'              )              }              let              (              :uploader              )              {              MyUploader              .              new              (              user              ,              :avatar              )              }              before              do              MyUploader              .              enable_processing              =              true              File              .              open              (              path_to_file              )              {              |f|              uploader              .              shop!              (              f              )              }              end              after              do              MyUploader              .              enable_processing              =              faux              uploader              .              remove!              end              context              'the thumb version'              do              it              "scales downwards a landscape image to be exactly 64 past 64 pixels"              do              expect              (              uploader              .              thumb              )              .              to              have_dimensions              (              64              ,              64              )              end              cease              context              'the small-scale version'              do              it              "scales down a landscape image to fit within 200 by 200 pixels"              do              expect              (              uploader              .              modest              )              .              to              be_no_larger_than              (              200              ,              200              )              cease              finish              it              "makes the prototype readable but to the owner and not executable"              do              wait              (              uploader              )              .              to              have_permissions              (              0600              )              cease              it              "has the right format"              do              expect              (              uploader              )              .              to              be_format              (              'png'              )              end              cease            

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

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

              @uploader              .              thumb              .              enable_processing              =              truthful            

Fog

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

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

Using Amazon S3

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

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

              CarrierWave              .              configure              do              |config|              config              .              fog_credentials              =              {              provider:              'AWS'              ,              # required              aws_access_key_id:              'thirty'              ,              # required unless using use_iam_profile              aws_secret_access_key:              'yyy'              ,              # required unless using use_iam_profile              use_iam_profile:              truthful              ,              # optional, defaults to false              region:              'eu-w-1'              ,              # optional, defaults to 'united states-e-one'              host:              's3.example.com'              ,              # optional, defaults to nil              endpoint:              'https://s3.example.com:8080'              # optional, defaults to aught              }              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 merely does non need caches persisted across requests,              # uncomment the line :file instead of the default :storage.  Otherwise, it volition use AWS as the temp cache shop.              # config.cache_storage = :file              stop            

In your uploader, set the storage to :fog

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

That's it! You lot tin notwithstanding apply the CarrierWave::Uploader#url method to render the url to the file on Amazon S3.

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

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

Using Rackspace Deject Files

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

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

Using a United states-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 Great britain-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'              terminate            

You tin can 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, fix the storage to :fog

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

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

Using Google Cloud Storage

Fog is used to support Google Cloud Storage. Ensure y'all have it in your Gemfile:

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

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

For Google Storage JSON API (recommended):

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

For Google Storage XML API:

              CarrierWave              .              configure              practise              |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'              terminate            

In your uploader, set the storage to :fog

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

That'south information technology! Y'all tin however 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 y'all intend to use, information technology will simply load the unabridged library (unless you employ e.1000. [fog-aws, fog-google] instead of fog proper). If you prefer to load fewer classes into your application, you need to load those parts of Fog yourself before loading CarrierWave in your Gemfile. Ex:

              jewel              "fog"              ,              "~> one.27"              ,              require:              "fog/rackspace/storage"              precious stone              "carrierwave"            

A couple of notes nearly versions:

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

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

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

Beware that this specific require is just needed when working with a fog provider that was non extracted to its ain gem yet. A listing of the extracted providers can be found 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 anything 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 as its only argument.

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

Using RMagick

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

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

The RMagick module gives you a few methods, similar CarrierWave::RMagick#resize_to_fill which manipulate the image file in some way. You lot can set a process callback, which will call that method any time a file is uploaded. There is a demonstration of catechumen here. Convert volition but work if the file has the same file extension, thus the use of the filename method.

              class              AvatarUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::RMagick              procedure              resize_to_fill:              [              200              ,              200              ]              process              convert:              'png'              def              filename              super              .              chomp              (              File              .              extname              (              super              )              )              +              '.png'              if              original_filename              .              present?              end              end            

Bank check out the manipulate! method, which makes it like shooting fish in a barrel for y'all to write your own manipulation methods.

Using MiniMagick

MiniMagick is similar to RMagick just performs all the operations using the 'catechumen' CLI which is part of the standard ImageMagick kit. This allows you to take 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 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 every bit for the RMagick processor.

              class              AvatarUploader              <              CarrierWave::Uploader::Base              include              CarrierWave::MiniMagick              procedure              resize_to_fill:              [              200              ,              200              ]              terminate            

Migrating from Paperclip

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

              form              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 Tape validations use 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 immune file type              carrierwave_download_error:              could not be downloaded              extension_allowlist_error:                              "You are not allowed to upload %{extension} files, allowed types: %{allowed_types}"                            extension_denylist_error:                              "You are non allowed to upload %{extension} files, prohibited types: %{prohibited_types}"                            content_type_allowlist_error:                              "You are not allowed to upload %{content_type} files, immune types: %{allowed_types}"                            content_type_denylist_error:                              "You are not allowed to upload %{content_type} files"                            processing_error:                              "Failed to manipulate, maybe it is not an image?"                            min_size_error:                              "File size should be greater than %{min_size}"                            max_size_error:                              "File size should be less than %{max_size}"                          

The carrierwave-i18n library adds support for additional locales.

Big files

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

You may change this beliefs past 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              finish              finish            

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

This has only been tested with the local filesystem store.

Skipping ActiveRecord callbacks

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

              form              User              mount_uploader              :avatar              ,              AvatarUploader              cease            

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 continue the existing avatar, even later on uploading a new one), y'all can use ActiveRecord'due south skip_callback method.

              class              User              mount_uploader              :avatar              ,              AvatarUploader              skip_callback              :commit              ,              :afterward              ,              :remove_previously_stored_avatar              finish            

Uploader Callbacks

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

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

Uploader callbacks can be before or subsequently the post-obit events:

              enshroud process remove retrieve_from_cache store                          

Contributing to CarrierWave

See CONTRIBUTING.doc

License

The MIT License (MIT)

Copyright (c) 2008-2015 Jonas Nicklas

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

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

THE SOFTWARE IS PROVIDED "Every bit IS", WITHOUT WARRANTY OF Whatever KIND, EXPRESS OR Unsaid, INCLUDING BUT Non Express TO THE WARRANTIES OF MERCHANTABILITY, Fettle FOR A Detail PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS Be LIABLE FOR Whatsoever CLAIM, Damages 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.

beardcitter.blogspot.com

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

Post a Comment for "Awss3errorsaccessdenied When Uploading the Image Rails Carrier Wave"