Upload Multiple Files Carrierwave Ruby on Rails

CarrierWave

This gem provides a simple and extremely flexible fashion to upload files from Blood-red applications. It works well with Rack based web applications, such every bit Ruddy on Rails.

Build Status Code Climate SemVer

Information

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

Getting Aid

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

Installation

Install the latest release:

          $ precious stone install carrierwave                  

In Track, add it to your Gemfile:

                      gem                          '              carrierwave              '                        ,                          '              ~> 2.0              '                              

Finally, restart the server to apply the changes.

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

Getting Started

Kickoff off past generating an uploader:

                      rails            generate            uploader            Avatar                  

this should requite yous a file in:

                      app            /            uploaders            /            avatar_uploader            .            rb                  

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

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

Y'all can employ your uploader course to store and recall files similar 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 cache for temporary storage. You tin use different stores, including filesystem and cloud storage.

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

ActiveRecord

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

                      crave                          '              carrierwave/orm/activerecord              '                              

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

                      rail            one thousand            migration            add_avatar_to_users            avatar:            string            rails            db:            migrate                  

Open up your model file and mount the uploader:

                      class            User            <            ApplicationRecord                          mount_uploader                        :avatar            ,            AvatarUploader            end                  

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

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

Note: u.avatar will never render nil, even if there is no photo associated to information technology. To bank check if a photo was saved to the model, use u.avatar.file.null? 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 also has convenient support for multiple file upload fields.

ActiveRecord

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

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

                      rails            g            migration            add_avatars_to_users            avatars:            json            rails            db:            drift                  

For database without ActiveRecord json information type support (eastward.g. SQLite)

                      rails            g            migration            add_avatars_to_users            avatars:            string            runway            db:            migrate                  

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

Open your model file and mount the uploader:

                      course            User            <            ApplicationRecord                          mount_uploaders                        :avatars            ,            AvatarUploader            serialize            :avatars            ,            JSON            # If y'all employ SQLite, add this line.                        stop                  

Brand certain that y'all mount the uploader with write (mount_uploaders) with s non (mount_uploader) in order to avoid errors when uploading multiple files

Make sure your file input fields are prepare up as multiple file fields. For instance in Rails you'll want to practice something like this:

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

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

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

Now yous can select multiple files in the upload dialog (due east.g. SHIFT+SELECT), and they volition automatically exist stored when the tape is saved.

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

If you lot want to preserve existing files on uploading new 1, you tin get similar:

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

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

Changing the storage directory

In club to change where uploaded files are put, only override the store_dir method:

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

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 you store files outside the projection root folder, you may want to define cache_dir in the aforementioned way:

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

Securing uploads

Sure files might exist dangerous if uploaded to the wrong location, such equally PHP files or other script files. CarrierWave allows yous to specify an allowlist of immune extensions or content types.

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

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

The same thing could be washed using content types. Allow'south say we need an uploader that accepts only images. This tin exist done similar this

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

Yous can use a denylist to pass up content types. Permit'due south say nosotros need an uploader that reject JSON files. This can be washed like this

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

CVE-2016-3714 (ImageTragick)

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

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

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

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

Filenames and unicode chars

Another security issue you should care for is the file names (encounter Ruddy On Rails Security Guide). By default, CarrierWave provides merely English letters, arabic numerals and some symbols every bit allowlisted characters in the file name. If you desire to support local scripts (Cyrillic letters, letters with diacritics and so on), you have to override sanitize_regexp method. It should render regular expression which would match all not-allowed symbols.

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

Also make certain that allowing non-latin characters won't cause a compatibility outcome with a tertiary-party plugins or client-side software.

Setting the content type

Equally of v0.eleven.0, the mime-types precious stone is a runtime dependency and the content type is fix automatically. You no longer need to do this manually.

Adding versions

Often you'll want to add together unlike versions of the aforementioned file. The classic example is image thumbnails. There is built in back up for this*:

Note: Yous must have Imagemagick installed to exercise prototype resizing.

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

To install Imagemagick on OSX with homebrew blazon the post-obit:

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

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

A version chosen :thumb is so created, which is scaled to exactly 200 by 200 pixels. The thumbnail uses resize_to_fill which makes sure that the width and pinnacle specified are filled, only cropping if the attribute ratio requires information technology.

The higher up uploader could exist used like this:

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

One important thing to call back is that process is chosen before versions are created. This can cut down on processing cost.

Processing Methods: mini_magick

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

See carrierwave/processing/mini_magick.rb for details.

conditional process

If you lot want to employ conditional process, y'all tin only use if statement.

See carrierwave/uploader/processing.rb for details.

                      form            MyUploader            <                          CarrierWave                        ::                          Uploader                        ::                          Base                        procedure            :scale            =>            [            200            ,            200            ]            ,            :if            =>            :prototype?            def            epitome?            (            carrier_wave_sanitized_file            )            true            cease            end                  

Nested versions

Information technology is possible to nest versions inside versions:

                      class            MyUploader            <                          CarrierWave                        ::                          Uploader                        ::                          Base of operations                        version            :animal            do            version            :man            version            :monkey            version            :llama            terminate            finish                  

Conditional versions

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

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

The model variable points to the instance object the uploader is attached 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 next is smaller than the terminal, it volition take less time to generate from a smaller, already processed image.

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

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

Making uploads work beyond course redisplays

Often yous'll notice that uploaded files disappear when a validation fails. CarrierWave has a feature that makes it easy to retrieve 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 as necessary). In Track, this would wait like this:

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

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

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

Removing uploaded files

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

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

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

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

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 simple, but add the appropriate attribute to your form and you're skillful to go:

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

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

Providing a default URL

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

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

Or if you are using the Runway asset pipeline:

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

Recreating versions

You might come to a situation where you want to retroactively alter a version or add together a new i. You tin 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 process the specified version or all versions, if none is passed equally an argument.

When you lot are generating random unique filenames you 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 system are running out of sync.

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

Or on a mounted uploader:

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

Annotation: recreate_versions! volition throw an exception on records without an image. To avoid this, telescopic the records to those with images or cheque if an paradigm exists within the cake. If you're using ActiveRecord, recreating versions for a user avatar might look like this:

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

Configuring CarrierWave

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

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

Or alternatively:

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

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

                      config            /            initializers            /            carrierwave            .            rb                  

If yous want CarrierWave to fail noisily in evolution, you lot tin can change these configs in your surroundings file:

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

Testing with CarrierWave

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

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

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

If y'all need to exam your processing, y'all should exam information technology in isolation, and enable processing just for those tests that need it.

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

                      require                          '              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 up            (            path_to_file            )            {            |            f            |            uploader            .            shop!            (            f            )            }            terminate            later on            do            MyUploader            .            enable_processing            =            false            uploader            .            remove!            terminate            context                          '              the thumb version              '                        do            information technology                          "              scales downwards a landscape image to be exactly 64 past 64 pixels              "                        do            await            (            uploader            .            thumb            )            .            to            have_dimensions            (            64            ,            64            )            end            end            context                          '              the small version              '                        do            it                          "              scales down a mural image to fit within 200 by 200 pixels              "                        exercise            wait            (            uploader            .            small            )            .            to            be_no_larger_than            (            200            ,            200            )            terminate            stop            it                          "              makes the paradigm readable only to the owner and non executable              "                        do            expect            (            uploader            )            .            to            have_permissions            (            0600            )            end            it                          "              has the correct format              "                        do            expect            (            uploader            )            .            to            be_format            (                          '              png              '                        )            end            finish                  

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

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

                      @uploader            .            thumb            .            enable_processing            =            true                  

Fog

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

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

Using Amazon S3

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

                      gem                          "              fog-aws              "                              

You'll need to provide your fog_credentials and a fog_directory (also known every bit a bucket) in an initializer. For the sake of operation it is causeless that the directory already exists, so please create it if it needs to be. Y'all tin can also pass in additional options, every bit documented fully in lib/carrierwave/storage/fog.rb. Here's a total 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:            true            ,            # optional, defaults to false                        region:                          '              european union-due west-1              '                        ,            # optional, defaults to 'us-due east-1'                        host:                          '              s3.example.com              '                        ,            # optional, defaults to nil                        endpoint:                          '              https://s3.instance.com:8080              '                        # optional, defaults to nothing                        }            config            .            fog_directory            =                          '              name_of_bucket              '                        # required                        config            .            fog_public            =            imitation            # optional, defaults to true                        config            .            fog_attributes            =            {            cache_control:                          "              public, max-age=              #{              365              .              days              .              to_i              }              "                        }            # optional, defaults to {}                        # For an application which utilizes multiple servers simply does non demand caches persisted across requests,                        # uncomment the line :file instead of the default :storage.  Otherwise, it will use AWS as the temp enshroud store.                        # config.cache_storage = :file                        end                  

In your uploader, prepare the storage to :fog

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

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

Notation: 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 back up Rackspace Cloud Files. Ensure you have information technology in your Gemfile:

                      gem                          "              fog              "                              

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

Using a Us-based account:

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

Using a United kingdom of great britain and northern ireland-based account:

                                    CarrierWave                        .                          configure                        practice            |            config            |            config            .            fog_credentials            =            {            provider:                          '              Rackspace              '                        ,            rackspace_username:                          '              xxxxxx              '                        ,            rackspace_api_key:                          '              yyyyyy              '                        ,            rackspace_auth_url:            Fog            ::            Rackspace            ::            UK_AUTH_ENDPOINT            ,            rackspace_region:            :lon            }            config            .            fog_directory            =                          '              name_of_directory              '                        stop                  

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

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

In your uploader, set the storage to :fog

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

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

Using Google Cloud Storage

Fog is used to back up Google Cloud Storage. Ensure you lot have information technology in your Gemfile:

                      gem                          "              fog-google              "                              

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

Please 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-projection              '                        ,            google_json_key_string:                          '              xxxxxx              '                        # or utilize google_json_key_location if using an actual file                        }            config            .            fog_directory            =                          '              google_cloud_storage_bucket_name              '                        terminate                  

For Google Storage XML API:

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

In your uploader, fix the storage to :fog

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

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

Optimized Loading of Fog

Since Carrierwave doesn't know which parts of Fog you intend to use, it volition just load the entire library (unless you use due east.g. [fog-aws, fog-google] instead of fog proper). If y'all prefer to load fewer classes into your application, you need to load those parts of Fog yourself earlier loading CarrierWave in your Gemfile. Ex:

                      gem                          "              fog              "                        ,                          "              ~> i.27              "                        ,            require:                          "              fog/rackspace/storage              "                        gem                          "              carrierwave              "                              

A couple of notes about versions:

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

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

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

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

When in doubt, 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 telephone call) for generating the host dynamically. The proc-compliant object gets an instance of the electric current CarrierWave::Storage::Fog::File or CarrierWave::SanitizedFile as its only argument.

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

Using RMagick

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

                      form            AvatarUploader            <                          CarrierWave                        ::                          Uploader                        ::                          Base of operations                        include                          CarrierWave                        ::                          RMagick                        end                  

The RMagick module gives yous a few methods, like CarrierWave::RMagick#resize_to_fill which manipulate the epitome file in some way. You tin ready a process callback, which will call that method any time a file is uploaded. In that location is a demonstration of convert hither. Catechumen will only piece of work if the file has the same file extension, thus the use of the filename method.

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

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

Using MiniMagick

MiniMagick is similar to RMagick just performs all the operations using the 'convert' CLI which is role of the standard ImageMagick kit. This allows you to have the power of ImageMagick without having to worry nigh 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 offering:

http://www.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            ]            terminate                  

Migrating from Paperclip

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

                      course            AvatarUploader            <                          CarrierWave                        ::                          Uploader                        ::                          Base                        include                          CarrierWave                        ::                          Compatibility                        ::                          Paperclip                        terminate                  

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

Exist certain to use mount_on to specify the correct column:

                                    mount_uploader                        :avatar            ,            AvatarUploader            ,            mount_on:            :avatar_file_name                  

I18n

The Agile Record 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: "Y'all are not allowed to upload %{extension} files, immune types: %{allowed_types}"     extension_denylist_error: "You are not immune 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 immune to upload %{content_type} files"     rmagick_processing_error: "Failed to dispense with rmagick, maybe it is not an image?"     mini_magick_processing_error: "Failed to dispense with MiniMagick, possibly it is non an image? Original Fault: %{east}"     min_size_error: "File size should be greater than %{min_size}"     max_size_error: "File size should exist less than %{max_size}"                  

The carrierwave-i18n library adds support for additional locales.

Large files

By default, CarrierWave copies an uploaded file twice, offset copying the file into the enshroud, then copying the file into the shop. For large files, this tin can exist prohibitively fourth dimension consuming.

You may change this behavior by overriding either or both of the move_to_cache and move_to_store methods:

                      class            MyUploader            <                          CarrierWave                        ::                          Uploader                        ::                          Base of operations                        def            move_to_cache            true            cease            def            move_to_store            true            stop            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 merely been tested with the local filesystem shop.

Skipping ActiveRecord callbacks

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

                      class            User                          mount_uploader                        :avatar            ,            AvatarUploader            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 desire to skip whatever of these callbacks (eg. yous want to keep the existing avatar, fifty-fifty after uploading a new one), you lot can use ActiveRecord's skip_callback method.

                      class            User                          mount_uploader                        :avatar            ,            AvatarUploader            skip_callback            :commit            ,            :later on            ,            :remove_previously_stored_avatar            finish                  

Contributing to CarrierWave

Come across CONTRIBUTING.md

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 restriction, including without limitation the rights to use, 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 do so, subject to the following conditions:

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Limited OR Implied, INCLUDING But NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Fettle FOR A Item PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 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 Utilise OR OTHER DEALINGS IN THE SOFTWARE.

pattonintentookey.blogspot.com

Source: https://www.rubydoc.info/gems/carrierwave/frames

0 Response to "Upload Multiple Files Carrierwave Ruby on Rails"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel