No Implicit Conversion of Uploader Into String Carrierwave
CarrierWave
This gem provides a uncomplicated and extremely flexible way to upload files from Blood-red applications. It works well with Rack based web applications, such equally Cherry-red on Runway.
Information
- RDoc documentation available on RubyDoc.info
- Source code available on GitHub
- More than data, known limitations, and how-tos available on the wiki
Getting Assist
- Please ask the community on Stack Overflow for assist if you lot take any questions. Delight do not mail usage questions on the effect tracker.
- Please written report bugs on the issue tracker merely read the "getting assistance" section in the wiki get-go.
Installation
Install the latest release:
$ gem install carrierwave
In Rails, add it to your Gemfile:
gem ' carrierwave ' , ' ~> ii.0 '
Finally, restart the server to apply the changes.
Every bit of version 2.0, CarrierWave requires Runway 5.0 or college and Ruby ii.two or higher. If you're on Runway 4, you should use 1.x.
Getting Started
Get-go off by generating an uploader:
track generate uploader Avatar
this should requite yous a file in:
app / uploaders / avatar_uploader . rb
Check out this file for some hints on how y'all can customize your uploader. It should wait something like this:
class AvatarUploader < CarrierWave :: Uploader :: Base storage :file terminate
You can use your uploader class to store and call back 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 lot can use different stores, including filesystem and cloud storage.
Nigh of the fourth dimension you lot are going to want to use CarrierWave together with an ORM. It is quite elementary to mount uploaders on columns in your model, and then yous tin simply assign files and get going:
ActiveRecord
Make sure you are loading CarrierWave afterward loading your ORM, otherwise you lot'll demand to crave the relevant extension manually, e.g.:
require ' carrierwave/orm/activerecord '
Add a string column to the model you want to mount the uploader by creating a migration:
rails 1000 migration add_avatar_to_users avatar: string track db: drift
Open your model file and mountain the uploader:
class User < ApplicationRecord mount_uploader :avatar , AvatarUploader end
At present you can cache files by assigning them to the aspect, 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 stop u . save! u . avatar . url # => '/url/to/file.png' u . avatar . current_path # => 'path/to/file.png' u . avatar_identifier # => 'file.png'
Note: u.avatar
volition never return zip, even if there is no photograph associated to it. To bank check if a photo was saved to the model, use u.avatar.file.nil?
instead.
DataMapper, Mongoid, Sequel
Other ORM support has been extracted into separate gems:
- carrierwave-datamapper
- carrierwave-mongoid
- carrierwave-sequel
In that location 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 can store an array. This could exist an array column or a JSON column for case. Your option depends on what your database supports. For example, create a migration like this:
For databases with ActiveRecord json information blazon support (eastward.one thousand. PostgreSQL, MySQL)
track g migration add_avatars_to_users avatars: json rails db: drift
For database without ActiveRecord json information blazon support (due east.1000. SQLite)
rails g migration add_avatars_to_users avatars: string track db: migrate
Notation: JSON datatype doesn't exists in SQLite adapter, that'south why you tin use a string datatype which will be serialized in model.
Open your model file and mount the uploader:
class User < ApplicationRecord mount_uploaders :avatars , AvatarUploader serialize :avatars , JSON # If yous use SQLite, add this line. end
Make sure that you mount the uploader with write (mount_uploaders) with s
not (mount_uploader) in social club to avoid errors when uploading multiple files
Make sure your file input fields are prepare as multiple file fields. For instance in Rails you'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 yous 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 . salvage! u . avatars [ 0 ] . url # => '/url/to/file.png' u . avatars [ 0 ] . current_path # => 'path/to/file.png' u . avatars [ 0 ] . identifier # => 'file.png'
If you desire to preserve existing files on uploading new one, y'all can go like:
<% user.avatars.each practise |avatar| %> <%= hidden_field :user, :avatars, multiple: true, value: avatar.identifier %> <% stop %> <%= form.file_field :avatars, multiple: truthful %>
Sorting avatars is supported as well by reordering hidden_field
, an instance using jQuery UI Sortable is available here.
Changing the storage directory
In guild to modify where uploaded files are put, just override the store_dir
method:
course MyUploader < CarrierWave :: Uploader :: Base def store_dir ' public/my/upload/directory ' end cease
This works for the file storage besides equally Amazon S3 and Rackspace Cloud Files. Define store_dir
equally nil
if you'd like to store files at the root level.
If you store files outside the project root binder, y'all may desire to ascertain cache_dir
in the same style:
course MyUploader < CarrierWave :: Uploader :: Base def cache_dir ' /tmp/projectname-enshroud ' end end
Securing uploads
Certain files might be dangerous if uploaded to the wrong location, such as PHP files or other script files. CarrierWave allows you to specify an allowlist of allowed extensions or content types.
If you lot're mounting the uploader, uploading a file with the wrong extension volition make the record invalid instead. Otherwise, an mistake is raised.
class MyUploader < CarrierWave :: Uploader :: Base def extension_allowlist %w( jpg jpeg gif png ) end end
The aforementioned thing could exist done using content types. Let'south say we demand an uploader that accepts simply images. This tin can be done like this
class MyUploader < CarrierWave :: Uploader :: Base def content_type_allowlist / prototype\/ / terminate end
Yous tin use a denylist to reject content types. Let'southward say we need an uploader that reject JSON files. This tin can be washed like this
form NoJsonUploader < CarrierWave :: Uploader :: Base def content_type_denylist [ ' application/text ' , ' awarding/json ' ] cease end
CVE-2016-3714 (ImageTragick)
This version of CarrierWave has the power to mitigate CVE-2016-3714. Withal, you 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 just, and mitigate the CVE is:
class MyUploader < CarrierWave :: Uploader :: Base def content_type_allowlist [ / epitome\/ / ] end finish
WARNING: A content_type_allowlist
is the only form of allowlist or denylist supported past CarrierWave that can effectively mitigate against CVE-2016-3714. Utilize of extension_allowlist
will not inspect the file headers, and thus still leaves your awarding open to the vulnerability.
Filenames and unicode chars
Another security upshot you lot should treat is the file names (see Ruby On Rails Security Guide). By default, CarrierWave provides but English letters, standard arabic numerals and some symbols equally allowlisted characters in the file proper name. If you want to support local scripts (Cyrillic letters, messages with diacritics and so on), yous have to override sanitize_regexp
method. It should render regular expression which would lucifer all non-allowed symbols.
CarrierWave :: SanitizedFile . sanitize_regexp = / [^[:give-and-take:]\.\-\+] /
Too brand sure that assuasive non-latin characters won't crusade a compatibility issue with a third-party plugins or client-side software.
Setting the content type
As of v0.11.0, the mime-types
precious stone is a runtime dependency and the content type is set automatically. You no longer need to do this manually.
Adding versions
Oft yous'll want to add different versions of the aforementioned file. The classic example is epitome thumbnails. There is built in back up for this*:
Note: You must have Imagemagick installed to do image resizing.
Some documentation refers to RMagick instead of MiniMagick simply MiniMagick is recommended.
To install Imagemagick on OSX with homebrew blazon the following:
$ mash install imagemagick
form MyUploader < CarrierWave :: Uploader :: Base include CarrierWave :: MiniMagick process resize_to_fit: [ 800 , 800 ] version :thumb do procedure resize_to_fill: [ 200 , 200 ] end cease
When this uploader is used, an uploaded image would be scaled to be no larger than 800 by 800 pixels. The original aspect ratio volition be kept.
A version called :thumb
is so created, which is scaled to exactly 200 by 200 pixels. The thumbnail uses resize_to_fill
which makes certain that the width and height specified are filled, but cropping if the aspect ratio requires it.
The in a higher place uploader could be used like this:
uploader = AvatarUploader . new uploader . store! ( my_file ) # size: 1024x768 uploader . url # => '/url/to/my_file.png' # size: 800x800 uploader . pollex . url # => '/url/to/thumb_my_file.png' # size: 200x200
1 important thing to call back is that process is called before versions are created. This can cut down on processing price.
Processing Methods: mini_magick
-
catechumen
- Changes the epitome 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 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 simply will not be larger than the specified values. -
resize_to_fit
- Resize the prototype to fit within the specified dimensions while retaining the original aspect ratio. The epitome may be shorter or narrower than specified in the smaller dimension but will non exist 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 image. If necessary, crop the epitome in the larger dimension. Optionally, a "gravity" may be specified, for example "Center", or "NorthEast". -
resize_and_pad
- Resize the epitome 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, equally to a higher place.
Meet carrierwave/processing/mini_magick.rb
for details.
conditional procedure
If you lot desire to utilize conditional procedure, you can but use if
argument.
See carrierwave/uploader/processing.rb
for details.
grade MyUploader < CarrierWave :: Uploader :: Base process :scale => [ 200 , 200 ] , :if => :image? def prototype? ( carrier_wave_sanitized_file ) truthful end end
Nested versions
It is possible to nest versions within versions:
class MyUploader < CarrierWave :: Uploader :: Base version :animate being do version :human version :monkey version :llama end end
Conditional versions
Occasionally y'all want to restrict the cosmos of versions on sure properties within the model or based on the movie itself.
course MyUploader < CarrierWave :: Uploader :: Base version :human , 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? film model . favorite_food == ' banana ' cease def is_landscape? picture show image = MiniMagick :: Prototype . new ( picture . path ) epitome [ :width ] > image [ :height ] end cease
The model
variable points to the example object the uploader is fastened 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 take less fourth dimension to generate from a smaller, already processed image.
class MyUploader < CarrierWave :: Uploader :: Base version :thumb exercise process resize_to_fill: [ 280 , 280 ] finish version :small_thumb , from_version: :thumb exercise process resize_to_fill: [ 20 , 20 ] cease end
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 across class redisplays
Oftentimes you'll notice that uploaded files disappear when a validation fails. CarrierWave has a feature that makes it easy to retrieve the uploaded file fifty-fifty 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 Rail, 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> <% end %>
It might be a adept thought to testify the user that a file has been uploaded, in the case of images, a small thumbnail would be a good indicator:
<%= form_for @user, html: { multipart: truthful } practice |f| %> <p> <characterization>My Avatar</characterization> <%= image_tag(@user.avatar_url) if @user.avatar? %> <%= f.file_field :avatar %> <%= f.hidden_field :avatar_cache %> </p> <% finish %>
Removing uploaded files
If you want to remove a previously uploaded file on a mounted uploader, yous can easily add a checkbox to the grade which volition remove the file when checked.
<%= form_for @user, html: { multipart: true } do |f| %> <p> <label>My Avatar</label> <%= image_tag(@user.avatar_url) if @user.avatar? %> <%= f.file_field :avatar %> </p> <p> <characterization> <%= f.check_box :remove_avatar %> Remove avatar </characterization> </p> <% end %>
If you lot want to remove the file manually, you can call remove_avatar!
, then relieve the object.
@user.remove_avatar! @user.salvage #=> true
Uploading files from a remote location
Your users may find it convenient to upload a file from a location on the Net via a URL. CarrierWave makes this simple, but add the advisable attribute to your course and you're practiced to get:
<%= form_for @user, html: { multipart: true } do |f| %> <p> <label>My Avatar URL:</characterization> <%= image_tag(@user.avatar_url) if @user.avatar? %> <%= f.text_field :remote_avatar_url %> </p> <% finish %>
If you're using ActiveRecord, CarrierWave volition indicate invalid URLs and download failures automatically with attribute validation errors. If you aren't, or you disable CarrierWave'southward validate_download
option, y'all'll need to handle those errors yourself.
Providing a default URL
In many cases, especially when working with images, it might be a practiced idea to provide a default url, a fallback in instance no file has been uploaded. You lot can do this easily by overriding the default_url
method in your uploader:
class MyUploader < CarrierWave :: Uploader :: Base of operations def default_url ( * args ) " /images/fallback/ " + [ version_name , " default.png " ] . meaty . join ( ' _ ' ) cease finish
Or if you are using the Rails asset pipeline:
class MyUploader < CarrierWave :: Uploader :: Base def default_url ( * args ) ActionController :: Base . helpers . asset_path ( " fallback/ " + [ version_name , " default.png " ] . meaty . join ( ' _ ' ) ) end terminate
Recreating versions
Yous might come up to a state of affairs where y'all want to retroactively change a version or add together a new one. You lot tin can use the recreate_versions!
method to recreate the versions from the base file. This uses a naive approach which volition re-upload and process the specified version or all versions, if none is passed equally an argument.
When you are generating random unique filenames you have to call salvage!
on the model afterward using recreate_versions!
. This is necessary considering recreate_versions!
doesn't save the new filename to the database. Calling salvage!
yourself will prevent that the database and file system are running out of sync.
instance = MyUploader . new example . recreate_versions! ( :pollex , :big )
Or on a mounted uploader:
User . find_each do | user | user . avatar . recreate_versions! end
Notation: recreate_versions!
will throw an exception on records without an image. To avoid this, scope the records to those with images or check if an image exists within the block. If you lot're using ActiveRecord, recreating versions for a user avatar might expect like this:
User . find_each practise | user | user . avatar . recreate_versions! if user . avatar? stop
Configuring CarrierWave
CarrierWave has a wide range of configuration options, which yous can configure, both globally and on a per-uploader basis:
CarrierWave . configure do | config | config . = 0666 config . = 0777 config . storage = :file end
Or alternatively:
class AvatarUploader < CarrierWave :: Uploader :: Base 0777 cease
If you're using Rails, create an initializer for this:
config / initializers / carrierwave . rb
If you want CarrierWave to fail noisily in development, yous can modify these configs in your environs file:
CarrierWave . configure practise | config | config . ignore_integrity_errors = false config . ignore_processing_errors = fake config . ignore_download_errors = faux finish
Testing with CarrierWave
It's a good idea to examination your uploaders in isolation. In order to speed up your tests, information technology's recommended to switch off processing in your tests, and to use the file storage. In Runway you lot could exercise that past calculation an initializer with:
if Track . env . exam? or Runway . env . cucumber? CarrierWave . configure practise | config | config . storage = :file config . enable_processing = simulated end end
Call up, if y'all take already set storage :something
in your uploader, the storage
setting from this initializer will be ignored.
If you need to examination your processing, you should exam it in isolation, and enable processing only for those tests that need it.
CarrierWave comes with some RSpec matchers which you lot may discover useful:
require ' carrierwave/examination/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 . store! ( f ) } end later practise MyUploader . enable_processing = false uploader . remove! end context ' the pollex version ' do it " scales downwards a landscape image to be exactly 64 by 64 pixels " do wait ( uploader . thumb ) . to have_dimensions ( 64 , 64 ) end end context ' the small version ' do it " scales downward a mural prototype to fit within 200 by 200 pixels " do wait ( uploader . modest ) . to be_no_larger_than ( 200 , 200 ) end terminate it " makes the image readable only to the possessor and not executable " do expect ( uploader ) . to ( 0600 ) terminate it " has the right format " do expect ( uploader ) . to be_format ( ' png ' ) end end
If you lot're looking for minitest asserts, checkout carrierwave_asserts.
Setting the enable_processing flag on an uploader will prevent any of the versions from processing as well. Processing can be enabled for a single version by setting the processing flag on the version similar and then:
@uploader . thumb . enable_processing = true
Fog
If you want to employ fog you must add 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 lot'll demand to provide your fog_credentials and a fog_directory (also known equally a bucket) in an initializer. For the sake of performance it is assumed that the directory already exists, so please create information technology if it needs to be. You can also pass in additional options, as documented fully in lib/carrierwave/storage/fog.rb. Here's a full instance:
CarrierWave . configure do | config | config . fog_credentials = { provider: ' AWS ' , # required aws_access_key_id: ' xxx ' , # required unless using use_iam_profile aws_secret_access_key: ' yyy ' , # required unless using use_iam_profile use_iam_profile: true , # optional, defaults to imitation region: ' eu-w-1 ' , # optional, defaults to 'us-east-1' host: ' s3.example.com ' , # optional, defaults to zilch endpoint: ' https://s3.example.com:8080 ' # optional, defaults to cypher } config . fog_directory = ' name_of_bucket ' # required config . fog_public = false # optional, defaults to true config . fog_attributes = { cache_control: " public, max-age= #{ 365 . days . to_i } " } # optional, defaults to {} # For an application which utilizes multiple servers but does not need caches persisted across requests, # uncomment the line :file instead of the default :storage. Otherwise, it will apply AWS as the temp cache store. # config.cache_storage = :file end
In your uploader, set the storage to :fog
class AvatarUploader < CarrierWave :: Uploader :: Base storage :fog stop
That's it! You can still use the CarrierWave::Uploader#url
method to return the url to the file on Amazon S3.
Note: for Carrierwave to work properly it needs credentials with the following permissions:
-
s3:ListBucket
-
s3:PutObject
-
s3:GetObject
-
s3:DeleteObject
-
s3:PutObjectAcl
Using Rackspace Cloud Files
Fog is used to support Rackspace Cloud Files. Ensure you have information technology in your Gemfile:
jewel " fog "
You'll need to configure a directory (also known as a container), username and API primal in the initializer. For the sake of performance it is assumed that the directory already exists, and so please create it if demand be.
Using a US-based account:
CarrierWave . configure practice | config | config . fog_credentials = { provider: ' Rackspace ' , rackspace_username: ' xxxxxx ' , rackspace_api_key: ' yyyyyy ' , rackspace_region: :ord # optional, defaults to :dfw } config . fog_directory = ' name_of_directory ' cease
Using a Uk-based account:
CarrierWave . configure do | config | config . fog_credentials = { provider: ' Rackspace ' , rackspace_username: ' xxxxxx ' , rackspace_api_key: ' yyyyyy ' , rackspace_auth_url: Fog :: Rackspace :: UK_AUTH_ENDPOINT , rackspace_region: :lon } config . fog_directory = ' name_of_directory ' end
Yous can optionally include your CDN host proper name in the configuration. This is highly recommended, equally without it every request requires a lookup of this information.
config . asset_host = " http://c000000.cdn.rackspacecloud.com "
In your uploader, ready the storage to :fog
class AvatarUploader < CarrierWave :: Uploader :: Base of operations storage :fog end
That's information technology! You tin can still utilize the CarrierWave::Uploader#url
method to render the url to the file on Rackspace Cloud Files.
Using Google Cloud Storage
Fog is used to support Google Deject Storage. Ensure you lot have it in your Gemfile:
gem " fog-google "
You'll need to configure a directory (besides known as a bucket) and the credentials in the initializer. For the sake of functioning it is assumed that the directory already exists, and then please create it if need 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-project ' , google_json_key_string: ' xxxxxx ' # or employ google_json_key_location if using an actual file } config . fog_directory = ' google_cloud_storage_bucket_name ' end
For Google Storage XML API:
CarrierWave . configure 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 ' stop
In your uploader, set the storage to :fog
grade AvatarUploader < CarrierWave :: Uploader :: Base storage :fog end
That's it! Y'all can withal use the CarrierWave::Uploader#url
method to render the url to the file on Google.
Optimized Loading of Fog
Since Carrierwave doesn't know which parts of Fog you intend to employ, it will merely load the entire library (unless you use east.1000. [fog-aws
, fog-google
] instead of fog proper). If you prefer to load fewer classes into your application, you demand to load those parts of Fog yourself before loading CarrierWave in your Gemfile. Ex:
precious stone " fog " , " ~> 1.27 " , crave: " fog/rackspace/storage " gem " carrierwave "
A couple of notes about versions:
- This functionality was introduced in Fog v1.20.
- This functionality is slated for CarrierWave v1.0.0.
If you're not relying on Gemfile entries alone and are requiring "carrierwave" anywhere, ensure you require "fog/rackspace/storage" before it. Ex:
require " fog/rackspace/storage " require " carrierwave "
Beware that this specific require is simply needed when working with a fog provider that was not extracted to its own jewel yet. A list of the extracted providers can be found in the folio of the fog
organizations here.
When in dubiousness, inspect Fog.constants
to meet what has been loaded.
Dynamic Asset Host
The asset_host
config property tin be assigned a proc (or anything that responds to call
) for generating the host dynamically. The proc-compliant object gets an instance of the electric current CarrierWave::Storage::Fog::File
or CarrierWave::SanitizedFile
equally its just argument.
CarrierWave . configure do | config | config . asset_host = proc do | file | identifier = # some logic " http:// #{ identifier } .cdn.rackspacecloud.com " end end
Using RMagick
If you lot're uploading images, y'all'll probably want to dispense them in some fashion, you lot might want to create thumbnail images for example. CarrierWave comes with a modest 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 dispense the image file in some way. Yous can set a process
callback, which volition call that method any time a file is uploaded. There is a demonstration of convert here. Convert will only work if the file has the aforementioned file extension, thus the utilize 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 end
Check out the manipulate! method, which makes it easy for yous to write your ain manipulation methods.
Using MiniMagick
MiniMagick is like to RMagick but performs all the operations using the 'convert' CLI which is role of the standard ImageMagick kit. This allows you to take the ability of ImageMagick without having to worry about installing all the RMagick libraries.
See the MiniMagick site for more details:
https://github.com/minimagick/minimagick
And the ImageMagick command line options for more than for whats on offer:
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 of operations include CarrierWave :: MiniMagick process resize_to_fill: [ 200 , 200 ] end
Migrating from Paperclip
If y'all are using Paperclip, you lot tin use the provided compatibility module:
class AvatarUploader < CarrierWave :: Uploader :: Base include CarrierWave :: Compatibility :: Paperclip end
Run into the documentation for CarrierWave::Compatibility::Paperclip
for more than details.
Be sure to use mount_on to specify the correct cavalcade:
mount_uploader :avatar , AvatarUploader , mount_on: :avatar_file_name
I18n
The Active Record validations utilise the Rail i18n
framework. Add these keys to your translations file:
errors: letters: carrierwave_processing_error: failed to be candy carrierwave_integrity_error: is not of an allowed file type carrierwave_download_error: could non be downloaded extension_allowlist_error: "You are not allowed to upload %{extension} files, immune types: %{allowed_types}" extension_denylist_error: "Y'all are not allowed to upload %{extension} files, prohibited types: %{prohibited_types}" content_type_allowlist_error: "You are non 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 manipulate with rmagick, mayhap it is not an image?" mini_magick_processing_error: "Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: %{e}" 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.
Big files
By default, CarrierWave copies an uploaded file twice, commencement copying the file into the cache, then copying the file into the store. For large files, this can be prohibitively time consuming.
You may change this beliefs past overriding either or both of the move_to_cache
and move_to_store
methods:
form MyUploader < CarrierWave :: Uploader :: Base def move_to_cache true finish def move_to_store true end end
When the move_to_cache
and/or move_to_store
methods return true, files volition be 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 a few callbacks. For instance, this lawmaking:
class User mount_uploader :avatar , AvatarUploader end
Will add together 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 yous want to skip whatsoever of these callbacks (eg. you want to continue the existing avatar, fifty-fifty after uploading a new one), you can use ActiveRecord'south skip_callback
method.
class User mount_uploader :avatar , AvatarUploader skip_callback :commit , :later , :remove_previously_stored_avatar stop
Contributing to CarrierWave
See CONTRIBUTING.md
License
The MIT License (MIT)
Copyright (c) 2008-2015 Jonas Nicklas
Permission is hereby granted, free of accuse, to any person obtaining a re-create 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, subject to the post-obit conditions:
The in a higher place copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF Whatever KIND, EXPRESS OR IMPLIED, INCLUDING BUT Not LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Fitness FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS Be LIABLE FOR ANY CLAIM, 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.
Source: https://www.rubydoc.info/gems/carrierwave/frames
0 Response to "No Implicit Conversion of Uploader Into String Carrierwave"
Post a Comment