{"id":13400443,"url":"https://github.com/carrierwaveuploader/carrierwave","last_synced_at":"2025-05-12T18:22:32.442Z","repository":{"id":426955,"uuid":"47087","full_name":"carrierwaveuploader/carrierwave","owner":"carrierwaveuploader","description":"Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks","archived":false,"fork":false,"pushed_at":"2025-04-13T06:02:55.000Z","size":5149,"stargazers_count":8785,"open_issues_count":43,"forks_count":1661,"subscribers_count":137,"default_branch":"master","last_synced_at":"2025-05-05T15:51:03.813Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://github.com/carrierwaveuploader/carrierwave","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/carrierwaveuploader.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2008-08-28T18:39:49.000Z","updated_at":"2025-05-03T09:50:21.000Z","dependencies_parsed_at":"2023-07-12T16:32:07.971Z","dependency_job_id":"48df4c60-9f46-4d4d-a166-dea141abf273","html_url":"https://github.com/carrierwaveuploader/carrierwave","commit_stats":{"total_commits":2061,"total_committers":457,"mean_commits":"4.5098468271334795","dds":0.7472100921882581,"last_synced_commit":"f0620919d00dbd74d31e6b48f62346d6090e88f7"},"previous_names":["jnicklas/carrierwave"],"tags_count":86,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carrierwaveuploader%2Fcarrierwave","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carrierwaveuploader%2Fcarrierwave/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carrierwaveuploader%2Fcarrierwave/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carrierwaveuploader%2Fcarrierwave/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/carrierwaveuploader","download_url":"https://codeload.github.com/carrierwaveuploader/carrierwave/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252666473,"owners_count":21785260,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T19:00:52.087Z","updated_at":"2025-05-12T18:22:32.418Z","avatar_url":"https://github.com/carrierwaveuploader.png","language":"Ruby","readme":"# CarrierWave\n\nThis gem provides a simple and extremely flexible way to upload files from Ruby applications.\nIt works well with Rack based web applications, such as Ruby on Rails.\n\n[![Build Status](https://github.com/carrierwaveuploader/carrierwave/workflows/Test/badge.svg)](https://github.com/carrierwaveuploader/carrierwave/actions)\n[![Code Climate](https://codeclimate.com/github/carrierwaveuploader/carrierwave.svg)](https://codeclimate.com/github/carrierwaveuploader/carrierwave)\n[![SemVer](https://api.dependabot.com/badges/compatibility_score?dependency-name=carrierwave\u0026package-manager=bundler\u0026version-scheme=semver)](https://dependabot.com/compatibility-score.html?dependency-name=carrierwave\u0026package-manager=bundler\u0026version-scheme=semver)\n\n\n## Information\n\n* RDoc documentation [available on RubyDoc.info](https://rubydoc.info/gems/carrierwave)\n* Source code [available on GitHub](http://github.com/carrierwaveuploader/carrierwave)\n* More information, known limitations, and how-tos [available on the wiki](https://github.com/carrierwaveuploader/carrierwave/wiki)\n\n## Getting Help\n\n* Please ask the community on [Stack Overflow](https://stackoverflow.com/questions/tagged/carrierwave) for help if you have any questions. Please do not post usage questions on the issue tracker.\n* Please report bugs on the [issue tracker](http://github.com/carrierwaveuploader/carrierwave/issues) but read the \"getting help\" section in the wiki first.\n\n## Installation\n\nInstall the latest release:\n\n```\n$ gem install carrierwave\n```\n\nIn Rails, add it to your Gemfile:\n\n```ruby\ngem 'carrierwave', '~\u003e 3.0'\n```\n\nFinally, restart the server to apply the changes.\n\n## Upgrading from 2.x or earlier\n\nCarrierWave 3.0 comes with a change in the way of handling the file extension on conversion. This results in following issues if you use `process convert: :format` to change the file format:\n\n- If you have it on the uploader itself (not within a version), the file extension of the cached file will change. That means if you serve both CarrierWave 2.x and 3.x simultaneously on the same workload (e.g. using blue-green deployment), a cache file stored by 2.x can't be retrieved by 3.x and vice versa.\n- If you have it within a version, the file extension of the stored file will change. You need to perform `#recreate_versions!` to make it usable again.\n\nTo preserve the 2.x behavior, you can set `force_extension false` right after calling `process convert: :format`. See [#2659](https://github.com/carrierwaveuploader/carrierwave/pull/2659) for the detail.\n\n## Getting Started\n\nStart off by generating an uploader:\n\n\trails generate uploader Avatar\n\nthis should give you a file in:\n\n\tapp/uploaders/avatar_uploader.rb\n\nCheck out this file for some hints on how you can customize your uploader. It\nshould look something like this:\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  storage :file\nend\n```\n\nYou can use your uploader class to store and retrieve files like this:\n\n```ruby\nuploader = AvatarUploader.new\n\nuploader.store!(my_file)\n\nuploader.retrieve_from_store!('my_file.png')\n```\n\nCarrierWave gives you a `store` for permanent storage, and a `cache` for\ntemporary storage. You can use different stores, including filesystem\nand cloud storage.\n\nMost of the time you are going to want to use CarrierWave together with an ORM.\nIt is quite simple to mount uploaders on columns in your model, so you can\nsimply assign files and get going:\n\n### ActiveRecord\n\nMake sure you are loading CarrierWave after loading your ORM, otherwise you'll\nneed to require the relevant extension manually, e.g.:\n\n```ruby\nrequire 'carrierwave/orm/activerecord'\n```\n\nAdd a string column to the model you want to mount the uploader by creating\na migration:\n\n\n\trails g migration add_avatar_to_users avatar:string\n\trails db:migrate\n\nOpen your model file and mount the uploader:\n\n```ruby\nclass User \u003c ApplicationRecord\n  mount_uploader :avatar, AvatarUploader\nend\n```\n\nNow you can cache files by assigning them to the attribute, they will\nautomatically be stored when the record is saved.\n\n```ruby\nu = User.new\nu.avatar = params[:file] # Assign a file like this, or\n\n# like this\nFile.open('somewhere') do |f|\n  u.avatar = f\nend\n\nu.save!\nu.avatar.url # =\u003e '/url/to/file.png'\nu.avatar.current_path # =\u003e 'path/to/file.png'\nu.avatar_identifier # =\u003e 'file.png'\n```\n\n**Note**: `u.avatar` will never return nil, even if there is no photo associated to it.\nTo check if a photo was saved to the model, use `u.avatar.file.nil?` instead.\n\n### DataMapper, Mongoid, Sequel\n\nOther ORM support has been extracted into separate gems:\n\n* [carrierwave-datamapper](https://github.com/carrierwaveuploader/carrierwave-datamapper)\n* [carrierwave-mongoid](https://github.com/carrierwaveuploader/carrierwave-mongoid)\n* [carrierwave-sequel](https://github.com/carrierwaveuploader/carrierwave-sequel)\n\nThere are more extensions listed in [the wiki](https://github.com/carrierwaveuploader/carrierwave/wiki)\n\n## Multiple file uploads\n\nCarrierWave also has convenient support for multiple file upload fields.\n\n### ActiveRecord\n\nAdd a column which can store an array. This could be an array column or a JSON\ncolumn for example. Your choice depends on what your database supports. For\nexample, create a migration like this:\n\n\n#### For databases with ActiveRecord json data type support (e.g. PostgreSQL, MySQL)\n\n\trails g migration add_avatars_to_users avatars:json\n\trails db:migrate\n\n#### For database without ActiveRecord json data type support (e.g. SQLite)\n\n\trails g migration add_avatars_to_users avatars:string\n\trails db:migrate\n\n__Note__: JSON datatype doesn't exists in SQLite adapter, that's why you can use a string datatype which will be serialized in model.\n\nOpen your model file and mount the uploader:\n\n\n```ruby\nclass User \u003c ApplicationRecord\n  mount_uploaders :avatars, AvatarUploader\n  serialize :avatars, JSON # If you use SQLite, add this line.\nend\n```\n\nMake sure that you mount the uploader with write (mount_uploaders) with `s` not (mount_uploader)\nin order to avoid errors when uploading multiple files\n\nMake sure your file input fields are set up as multiple file fields. For\nexample in Rails you'll want to do something like this:\n\n```erb\n\u003c%= form.file_field :avatars, multiple: true %\u003e\n```\n\nAlso, make sure your upload controller permits the multiple file upload attribute, *pointing to an empty array in a hash*. For example:\n\n```ruby\nparams.require(:user).permit(:email, :first_name, :last_name, {avatars: []})\n```\n\nNow you can select multiple files in the upload dialog (e.g. SHIFT+SELECT), and they will\nautomatically be stored when the record is saved.\n\n```ruby\nu = User.new(params[:user])\nu.save!\nu.avatars[0].url # =\u003e '/url/to/file.png'\nu.avatars[0].current_path # =\u003e 'path/to/file.png'\nu.avatars[0].identifier # =\u003e 'file.png'\n```\n\nIf you want to preserve existing files on uploading new one, you can go like:\n\n```erb\n\u003c% user.avatars.each do |avatar| %\u003e\n  \u003c%= hidden_field :user, :avatars, multiple: true, value: avatar.identifier %\u003e\n\u003c% end %\u003e\n\u003c%= form.file_field :avatars, multiple: true %\u003e\n```\n\nSorting avatars is supported as well by reordering `hidden_field`, an example using jQuery UI Sortable is available [here](https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Add%2C-remove-and-reorder-images-using-multiple-file-upload).\n\n## Changing the storage directory\n\nIn order to change where uploaded files are put, just override the `store_dir`\nmethod:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def store_dir\n    'public/my/upload/directory'\n  end\nend\n```\n\nThis works for the file storage as well as Amazon S3 and Rackspace Cloud Files.\nDefine `store_dir` as `nil` if you'd like to store files at the root level.\n\nIf you store files outside the project root folder, you may want to define `cache_dir` in the same way:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def cache_dir\n    '/tmp/projectname-cache'\n  end\nend\n```\n\n## Changing the filename\n\nTo change the filename of uploaded files, you can override `#filename` method in the uploader.\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def filename\n    \"image.#{file.extension}\" # If you upload 'file.jpg', you'll get 'image.jpg'\n  end\nend\n```\n\nSome old documentations (like [this](https://stackoverflow.com/a/5865117)) may instruct you to safeguard the filename value with `if original_filename`, but it's no longer necessary with CarrierWave 3.0 or later.\n\n## Securing uploads\n\nCertain files might be dangerous if uploaded to the wrong location, such as PHP\nfiles or other script files. CarrierWave allows you to specify an allowlist of\nallowed extensions or content types.\n\nIf you're mounting the uploader, uploading a file with the wrong extension will\nmake the record invalid instead. Otherwise, an error is raised.\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def extension_allowlist\n    %w(jpg jpeg gif png)\n  end\nend\n```\n\nThe same thing could be done using content types.\nLet's say we need an uploader that accepts only images. This can be done like this\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def content_type_allowlist\n    /image\\//\n  end\nend\n```\n\nYou can use a denylist to reject content types.\nLet's say we need an uploader that reject JSON files. This can be done like this\n\n```ruby\nclass NoJsonUploader \u003c CarrierWave::Uploader::Base\n  def content_type_denylist\n    ['application/text', 'application/json']\n  end\nend\n```\n\n### CVE-2016-3714 (ImageTragick)\nThis version of CarrierWave has the ability to mitigate CVE-2016-3714. However, you **MUST** set a content_type_allowlist in your uploaders for this protection to be effective, and you **MUST** either disable ImageMagick's default SVG delegate or use the RSVG delegate for SVG processing.\n\n\nA valid allowlist that will restrict your uploader to images only, and mitigate the CVE is:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def content_type_allowlist\n    [/image\\//]\n  end\nend\n```\n\n**WARNING**: A `content_type_allowlist` is the only form of allowlist or denylist supported by CarrierWave that can effectively mitigate against CVE-2016-3714. Use of `extension_allowlist` will not inspect the file headers, and thus still leaves your application open to the vulnerability.\n\n### Filenames and unicode chars\n\nAnother security issue you should care for is the file names (see\n[Ruby On Rails Security Guide](http://guides.rubyonrails.org/security.html#file-uploads)).\nBy default, CarrierWave provides only English letters, arabic numerals and some symbols as\nallowlisted characters in the file name. If you want to support local scripts (Cyrillic letters, letters with diacritics and so on), you\nhave to override `sanitize_regexp` method. It should return regular expression which would match\nall *non*-allowed symbols.\n\n```ruby\nCarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\\.\\-\\+]/\n```\n\nAlso make sure that allowing non-latin characters won't cause a compatibility issue with a third-party\nplugins or client-side software.\n\n## Setting the content type\n\nAs of v0.11.0, the `mime-types` gem is a runtime dependency and the content type is set automatically.\nYou no longer need to do this manually.\n\n## Adding versions\n\nOften you'll want to add different versions of the same file. The classic example is generating image thumbnails while preserving the original file to be used for high-quality representation.\nIn this section we'll explore how CarrierWave supports working with multiple versions. The image manipulation itself is covered in [another section](#manipulating-images).\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  include CarrierWave::MiniMagick\n\n  process resize_to_fit: [800, 800]\n\n  version :thumb do\n    process resize_to_fill: [200,200]\n  end\n\nend\n```\n\nWhen this uploader is used, an uploaded image would be scaled to be no larger\nthan 800 by 800 pixels. The original aspect ratio will be kept.\n\nA version called `:thumb` is then created, which is scaled\nto exactly 200 by 200 pixels. The thumbnail uses `resize_to_fill` which makes sure\nthat the width and height specified are filled, only cropping\nif the aspect ratio requires it.\n\nThe above uploader could be used like this:\n\n```ruby\nuploader = AvatarUploader.new\nuploader.store!(my_file)                              # size: 1024x768\n\nuploader.url # =\u003e '/url/to/my_file.png'               # size: 800x800\nuploader.thumb.url # =\u003e '/url/to/thumb_my_file.png'   # size: 200x200\n```\n\nOne important thing to remember is that process is called *before* versions are\ncreated. This can cut down on processing cost.\n\n### Conditional processing\n\nIf you want to use conditional process, you can only use `if` statement.\n\nSee `carrierwave/uploader/processing.rb` for details.\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  process :scale =\u003e [200, 200], :if =\u003e :image?\n  \n  def image?(carrier_wave_sanitized_file)\n    true\n  end\nend\n```\n\n### Nested versions\n\nIt is possible to nest versions within versions:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n\n  version :animal do\n    version :human\n    version :monkey\n    version :llama\n  end\nend\n```\n\n### Conditional versions\n\nOccasionally you want to restrict the creation of versions on certain\nproperties within the model or based on the picture itself.\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n\n  version :human, if: :is_human?\n  version :monkey, if: :is_monkey?\n  version :banner, if: :is_landscape?\n\nprivate\n\n  def is_human? picture\n    model.can_program?(:ruby)\n  end\n\n  def is_monkey? picture\n    model.favorite_food == 'banana'\n  end\n\n  def is_landscape? picture\n    image = MiniMagick::Image.new(picture.path)\n    image[:width] \u003e image[:height]\n  end\n\nend\n```\n\nThe `model` variable points to the instance object the uploader is attached to.\n\n### Create versions from existing versions\n\nFor performance reasons, it is often useful to create versions from existing ones\ninstead of using the original file. If your uploader generates several versions\nwhere the next is smaller than the last, it will take less time to generate from\na smaller, already processed image.\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n\n  version :thumb do\n    process resize_to_fill: [280, 280]\n  end\n\n  version :small_thumb, from_version: :thumb do\n    process resize_to_fill: [20, 20]\n  end\n\nend\n```\n\n### Customizing version filenames\n\nCarrierWave supports [customization of filename](#changing-the-filename) by overriding an uploader's\n#filename method, but this doesn't work for versions because of the limitation on how CarrierWave\nre-constructs the filename on retrieval of the stored file.\nInstead, you can override `#full_filename` with providing a version-aware name.\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  version :thumb do\n    def full_filename(for_file)\n      'thumb.png'\n    end\n    process convert: 'png'\n  end\nend\n```\n\nPlease note that `#full_filename` mustn't be constructed based on a dynamic value\nthat can change from the time of store and time of retrieval, since it will result in\nbeing unable to retrieve a file previously stored.\n\n## Making uploads work across form redisplays\n\nOften you'll notice that uploaded files disappear when a validation fails.\nCarrierWave has a feature that makes it easy to remember the uploaded file even\nin that case. Suppose your `user` model has an uploader mounted on `avatar`\nfile, just add a hidden field called `avatar_cache` (don't forget to add it to\nthe attr_accessible list as necessary). In Rails, this would look like this:\n\n```erb\n\u003c%= form_for @user, html: { multipart: true } do |f| %\u003e\n  \u003cp\u003e\n    \u003clabel\u003eMy Avatar\u003c/label\u003e\n    \u003c%= f.file_field :avatar %\u003e\n    \u003c%= f.hidden_field :avatar_cache %\u003e\n  \u003c/p\u003e\n\u003c% end %\u003e\n````\n\nIt might be a good idea to show the user that a file has been uploaded, in the\ncase of images, a small thumbnail would be a good indicator:\n\n```erb\n\u003c%= form_for @user, html: { multipart: true } do |f| %\u003e\n  \u003cp\u003e\n    \u003clabel\u003eMy Avatar\u003c/label\u003e\n    \u003c%= image_tag(@user.avatar_url) if @user.avatar? %\u003e\n    \u003c%= f.file_field :avatar %\u003e\n    \u003c%= f.hidden_field :avatar_cache %\u003e\n  \u003c/p\u003e\n\u003c% end %\u003e\n```\n\n## Removing uploaded files\n\nIf you want to remove a previously uploaded file on a mounted uploader, you can\neasily add a checkbox to the form which will remove the file when checked.\n\n```erb\n\u003c%= form_for @user, html: { multipart: true } do |f| %\u003e\n  \u003cp\u003e\n    \u003clabel\u003eMy Avatar\u003c/label\u003e\n    \u003c%= image_tag(@user.avatar_url) if @user.avatar? %\u003e\n    \u003c%= f.file_field :avatar %\u003e\n  \u003c/p\u003e\n\n  \u003cp\u003e\n    \u003clabel\u003e\n      \u003c%= f.check_box :remove_avatar %\u003e\n      Remove avatar\n    \u003c/label\u003e\n  \u003c/p\u003e\n\u003c% end %\u003e\n```\n\nIf you want to remove the file manually, you can call \u003ccode\u003eremove_avatar!\u003c/code\u003e, then save the object.\n\n```erb\n@user.remove_avatar!\n@user.save\n#=\u003e true\n```\n\n## Uploading files from a remote location\n\nYour users may find it convenient to upload a file from a location on the Internet\nvia a URL. CarrierWave makes this simple, just add the appropriate attribute to your\nform and you're good to go:\n\n```erb\n\u003c%= form_for @user, html: { multipart: true } do |f| %\u003e\n  \u003cp\u003e\n    \u003clabel\u003eMy Avatar URL:\u003c/label\u003e\n    \u003c%= image_tag(@user.avatar_url) if @user.avatar? %\u003e\n    \u003c%= f.text_field :remote_avatar_url %\u003e\n  \u003c/p\u003e\n\u003c% end %\u003e\n```\n\nIf you're using ActiveRecord, CarrierWave will indicate invalid URLs and download\nfailures automatically with attribute validation errors. If you aren't, or you\ndisable CarrierWave's `validate_download` option, you'll need to handle those\nerrors yourself.\n\n### Retry option for download from remote location\nIf you want to retry the download from the Remote URL, enable the download_retry_count option, an error occurs during download, it will try to execute the specified number of times.\nThis option is effective when the remote destination is unstable.\n\n```rb\nCarrierWave.configure do |config|\n  config.download_retry_count = 3 # Default 0\n  config.download_retry_wait_time = 3 # Default 5\nend\n```\n\n## Providing a default URL\n\nIn many cases, especially when working with images, it might be a good idea to\nprovide a default url, a fallback in case no file has been uploaded. You can do\nthis easily by overriding the `default_url` method in your uploader:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def default_url(*args)\n    \"/images/fallback/\" + [version_name, \"default.png\"].compact.join('_')\n  end\nend\n```\n\nOr if you are using the Rails asset pipeline:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def default_url(*args)\n    ActionController::Base.helpers.asset_path(\"fallback/\" + [version_name, \"default.png\"].compact.join('_'))\n  end\nend\n```\n\n## Recreating versions\n\nYou might come to a situation where you want to retroactively change a version\nor add a new one. You can use the `recreate_versions!` method to recreate the\nversions from the base file. This uses a naive approach which will re-upload and\nprocess the specified version or all versions, if none is passed as an argument.\n\nWhen you are generating random unique filenames you have to call `save!` on\nthe model after using `recreate_versions!`. This is necessary because\n`recreate_versions!` doesn't save the new filename to the database. Calling\n`save!` yourself will prevent that the database and file system are running\nout of sync.\n\n```ruby\ninstance = MyUploader.new\ninstance.recreate_versions!(:thumb, :large)\n```\n\nOr on a mounted uploader:\n\n```ruby\nUser.find_each do |user|\n  user.avatar.recreate_versions!\nend\n```\n\nNote: `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're using ActiveRecord, recreating versions for a user avatar might look like this:\n\n```ruby\nUser.find_each do |user|\n  user.avatar.recreate_versions! if user.avatar?\nend\n```\n\n## Configuring CarrierWave\n\nCarrierWave has a broad range of configuration options, which you can configure,\nboth globally and on a per-uploader basis:\n\n```ruby\nCarrierWave.configure do |config|\n  config.permissions = 0666\n  config.directory_permissions = 0777\n  config.storage = :file\nend\n```\n\nOr alternatively:\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  permissions 0777\nend\n```\n\nIf you're using Rails, create an initializer for this:\n\n\tconfig/initializers/carrierwave.rb\n\nIf you want CarrierWave to fail noisily in development, you can change these configs in your environment file:\n\n```ruby\nCarrierWave.configure do |config|\n  config.ignore_integrity_errors = false\n  config.ignore_processing_errors = false\n  config.ignore_download_errors = false\nend\n```\n\n\n## Testing with CarrierWave\n\nIt's a good idea to test your uploaders in isolation. In order to speed up your\ntests, it's recommended to switch off processing in your tests, and to use the file storage.\nAlso, you can disable SSRF protection at your own risk using the `skip_ssrf_protection` configuration.\n\nIn Rails you could do that by adding an initializer with:\n\n```ruby\nif Rails.env.test? or Rails.env.cucumber?\n  CarrierWave.configure do |config|\n    config.storage = :file\n    config.enable_processing = false\n    config.skip_ssrf_protection = true\n  end\nend\n```\n\nRemember, if you have already set `storage :something` in your uploader, the `storage`\nsetting from this initializer will be ignored.\n\nIf you need to test your processing, you should test it in isolation, and enable\nprocessing only for those tests that need it.\n\nCarrierWave comes with some RSpec matchers which you may find useful:\n\n```ruby\nrequire 'carrierwave/test/matchers'\n\ndescribe MyUploader do\n  include CarrierWave::Test::Matchers\n\n  let(:user) { double('user') }\n  let(:uploader) { MyUploader.new(user, :avatar) }\n\n  before do\n    MyUploader.enable_processing = true\n    File.open(path_to_file) { |f| uploader.store!(f) }\n  end\n\n  after do\n    MyUploader.enable_processing = false\n    uploader.remove!\n  end\n\n  context 'the thumb version' do\n    it \"scales down a landscape image to be exactly 64 by 64 pixels\" do\n      expect(uploader.thumb).to have_dimensions(64, 64)\n    end\n  end\n\n  context 'the small version' do\n    it \"scales down a landscape image to fit within 200 by 200 pixels\" do\n      expect(uploader.small).to be_no_larger_than(200, 200)\n    end\n  end\n\n  it \"makes the image readable only to the owner and not executable\" do\n    expect(uploader).to have_permissions(0600)\n  end\n\n  it \"has the correct format\" do\n    expect(uploader).to be_format('png')\n  end\nend\n```\n\nIf you're looking for minitest asserts, checkout [carrierwave_asserts](https://github.com/hcfairbanks/carrierwave_asserts).\n\nSetting the enable_processing flag on an uploader will prevent any of the versions from processing as well.\nProcessing can be enabled for a single version by setting the processing flag on the version like so:\n\n```ruby\n@uploader.thumb.enable_processing = true\n```\n\n## Fog\n\nIf you want to use fog you must add in your CarrierWave initializer the\nfollowing lines\n\n```ruby\nconfig.fog_credentials = { ... } # Provider specific credentials\n```\n\n## Using Amazon S3\n\n[Fog AWS](http://github.com/fog/fog-aws) is used to support Amazon S3. Ensure you have it in your Gemfile:\n\n```ruby\ngem \"fog-aws\"\n```\n\nYou'll need to provide your fog_credentials and a fog_directory (also known as a bucket) in an initializer.\nFor the sake of performance it is assumed that the directory already exists, so please create it if it needs to be.\nYou can also pass in additional options, as documented fully in lib/carrierwave/storage/fog.rb. Here's a full example:\n\n```ruby\nCarrierWave.configure do |config|\n  config.fog_credentials = {\n    provider:              'AWS',                        # required\n    aws_access_key_id:     'xxx',                        # required unless using use_iam_profile\n    aws_secret_access_key: 'yyy',                        # required unless using use_iam_profile\n    use_iam_profile:       true,                         # optional, defaults to false\n    region:                'eu-west-1',                  # optional, defaults to 'us-east-1'\n    host:                  's3.example.com',             # optional, defaults to nil\n    endpoint:              'https://s3.example.com:8080' # optional, defaults to nil\n  }\n  config.fog_directory  = 'name_of_bucket'                                      # required\n  config.fog_public     = false                                                 # optional, defaults to true\n  config.fog_attributes = { cache_control: \"public, max-age=#{365.days.to_i}\" } # optional, defaults to {}\n  # Use this if you have AWS S3 ACLs disabled.\n  # config.fog_attributes = { 'x-amz-acl' =\u003e 'bucket-owner-full-control' }\n  # Use this if you have Google Cloud Storage uniform bucket-level access enabled.\n  # config.fog_attributes = { uniform: true }\n  # For an application which utilizes multiple servers but does not need caches persisted across requests,\n  # uncomment the line :file instead of the default :storage.  Otherwise, it will use AWS as the temp cache store.\n  # config.cache_storage = :file\nend\n```\n\nIn your uploader, set the storage to :fog\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  storage :fog\nend\n```\n\nThat's it! You can still use the `CarrierWave::Uploader#url` method to return the url to the file on Amazon S3.\n\n**Note**: for Carrierwave to work properly it needs credentials with the following permissions:\n\n* `s3:ListBucket`\n* `s3:PutObject`\n* `s3:GetObject`\n* `s3:DeleteObject`\n* `s3:PutObjectAcl`\n\n## Using Rackspace Cloud Files\n\n[Fog](http://github.com/fog/fog) is used to support Rackspace Cloud Files. Ensure you have it in your Gemfile:\n\n```ruby\ngem \"fog\"\n```\n\nYou'll need to configure a directory (also known as a container), username and API key in the initializer.\nFor the sake of performance it is assumed that the directory already exists, so please create it if needs to be.\n\nUsing a US-based account:\n\n```ruby\nCarrierWave.configure do |config|\n  config.fog_credentials = {\n    provider:           'Rackspace',\n    rackspace_username: 'xxxxxx',\n    rackspace_api_key:  'yyyyyy',\n    rackspace_region:   :ord                      # optional, defaults to :dfw\n  }\n  config.fog_directory = 'name_of_directory'\nend\n```\n\nUsing a UK-based account:\n\n```ruby\nCarrierWave.configure do |config|\n  config.fog_credentials = {\n    provider:           'Rackspace',\n    rackspace_username: 'xxxxxx',\n    rackspace_api_key:  'yyyyyy',\n    rackspace_auth_url: Fog::Rackspace::UK_AUTH_ENDPOINT,\n    rackspace_region:   :lon\n  }\n  config.fog_directory = 'name_of_directory'\nend\n```\n\nYou can optionally include your CDN host name in the configuration.\nThis is *highly* recommended, as without it every request requires a lookup\nof this information.\n\n```ruby\nconfig.asset_host = \"http://c000000.cdn.rackspacecloud.com\"\n```\n\nIn your uploader, set the storage to :fog\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  storage :fog\nend\n```\n\nThat's it! You can still use the `CarrierWave::Uploader#url` method to return\nthe url to the file on Rackspace Cloud Files.\n\n## Using Google Cloud Storage\n\n[Fog](http://github.com/fog/fog-google) is used to support Google Cloud Storage. Ensure you have it in your Gemfile:\n\n```ruby\ngem \"fog-google\"\n```\n\nYou'll need to configure a directory (also known as a bucket) and the credentials in the initializer.\nFor the sake of performance it is assumed that the directory already exists, so please create it if needs to be.\n\nPlease read the [fog-google README](https://github.com/fog/fog-google/blob/master/README.md) on how to get credentials.\n\nFor Google Storage JSON API (recommended):\n```ruby\nCarrierWave.configure do |config|\n    config.fog_credentials = {\n        provider:               'Google',\n        google_project:         'my-project',\n        google_json_key_string: 'xxxxxx'\n        # or use google_json_key_location if using an actual file\n    }\n    config.fog_directory = 'google_cloud_storage_bucket_name'\nend\n```\n\nFor Google Storage XML API:\n```ruby\nCarrierWave.configure do |config|\n    config.fog_credentials = {\n        provider:                         'Google',\n        google_storage_access_key_id:     'xxxxxx',\n        google_storage_secret_access_key: 'yyyyyy'\n    }\n    config.fog_directory = 'google_cloud_storage_bucket_name'\nend\n```\n\nIn your uploader, set the storage to :fog\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  storage :fog\nend\n```\n\nThat's it! You can still use the `CarrierWave::Uploader#url` method to return\nthe url to the file on Google.\n\n## Optimized Loading of Fog\n\nSince Carrierwave doesn't know which parts of Fog you intend to use, it will just load the entire library (unless you use e.g. [`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:\n\n```ruby\ngem \"fog\", \"~\u003e 1.27\", require: \"fog/rackspace/storage\"\ngem \"carrierwave\"\n```\n\nA couple of notes about versions:\n* This functionality was introduced in Fog v1.20.\n* This functionality is slated for CarrierWave v1.0.0.\n\nIf you're not relying on Gemfile entries alone and are requiring \"carrierwave\" anywhere, ensure you require \"fog/rackspace/storage\" before it.  Ex:\n\n```ruby\nrequire \"fog/rackspace/storage\"\nrequire \"carrierwave\"\n```\n\nBeware that this specific require is only needed when working with a fog provider that was not extracted to its own gem yet.\nA list of the extracted providers can be found in the page of the `fog` organizations [here](https://github.com/fog).\n\nWhen in doubt, inspect `Fog.constants` to see what has been loaded.\n\n## Dynamic Asset Host\n\nThe `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.\n\n```ruby\nCarrierWave.configure do |config|\n  config.asset_host = proc do |file|\n    identifier = # some logic\n    \"http://#{identifier}.cdn.rackspacecloud.com\"\n  end\nend\n```\n\n## Manipulating images\n\nIf you're uploading images, you'll probably want to manipulate them in some way,\nyou might want to create thumbnail images for example.\n\n### Using MiniMagick\n\nMiniMagick performs all the operations using the 'convert' CLI which is part of the standard ImageMagick kit.\nThis allows you to have the power of ImageMagick without having to worry about installing\nall the RMagick libraries, it often results in higher memory footprint.\n\nSee the MiniMagick site for more details:\n\nhttps://github.com/minimagick/minimagick\n\nTo install Imagemagick on OSX with homebrew type the following:\n\n```\n$ brew install imagemagick\n```\n\nAnd the ImageMagick command line options for more for what's on offer:\n\nhttp://www.imagemagick.org/script/command-line-options.php\n\nCurrently, the MiniMagick carrierwave processor provides exactly the same methods as\nfor the RMagick processor.\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  include CarrierWave::MiniMagick\n\n  process resize_to_fill: [200, 200]\nend\n```\n\nSee `carrierwave/processing/mini_magick.rb` for details.\n\n### Using RMagick\n\nCarrierWave also comes with support for RMagick, a well-known image processing library.\nTo use it, you'll need to include this in your Uploader:\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  include CarrierWave::RMagick\nend\n```\n\nThe RMagick module gives you a few methods, like\n`CarrierWave::RMagick#resize_to_fill` which manipulate the image file in some\nway. You can set a `process` callback, which will call that method any time a\nfile is uploaded.\nThere is a demonstration of convert here.\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  include CarrierWave::RMagick\n\n  process resize_to_fill: [200, 200]\n  process convert: 'png'\nend\n```\n\nCheck out the manipulate! method, which makes it easy for you to write your own\nmanipulation methods.\n\n### Using Vips\n\nCarrierWave version 2.2.0 added support for the `libvips` image processing library, through [ImageProcessing::Vips](https://github.com/janko/image_processing/blob/master/doc/vips.md). Its functionality matches that of the RMagick and MiniMagick processors, but it uses less memory and offers [faster processing](https://github.com/libvips/libvips/wiki/Speed-and-memory-use). To use the Vips processing module you must first install `libvips`, for example: \n\n````bash\n$ sudo apt install libvips\n````\n\nYou also need to tell your uploader to use Vips:\n\n````ruby\nclass ImageFileUploader \u003c CarrierWave::Uploader::Base\n  include CarrierWave::Vips\nend\n````\n\n### List of available processing methods:\n\n\u003e [!NOTE]\n\u003e While the intention is to provide uniform interfaces to all three processing libraries the availability and implementation of processing methods can \u003ca href=\"supported-processing-methods\"\u003evary slightly between them\u003c/a\u003e.\n\n- `convert` - Changes the image encoding format to the given format (eg. jpg). This operation is treated specially to trigger the change of the file extension, so it matches with the format of the resulting file.\n- `resize_to_limit` - Resize the image 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 will not be larger than the specified values.\n- `resize_to_fit` - Resize the image to fit within the specified dimensions while retaining the original aspect ratio. The image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values.\n- `resize_to_fill` - Resize the image to fit within the specified dimensions while retaining the aspect ratio of the original image. If necessary, crop the image in the larger dimension. Optionally, a \"gravity\" may be specified, for example \"Center\", or \"NorthEast\".\n- `resize_and_pad` - Resize the image 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, as above.\n- `crop` - Crop the image to the contents of a box with the specified height and width, positioned a given number of pixels from the top and left. The original image edge will be retained should the bottom and/or right edge of the box fall outside the image bounds. \n\n#### Supported processing methods\n\nThe following table shows which processing methods are supported by each processing library, and which parameters they accept: \n\nMethod|RMagick|MiniMagick|Vips\n------|-----------------|-----------------|-----------------|\n`convert`|`format`|`format`, `page`\u003csup\u003e1\u003c/sup\u003e|`format`, `page`\u003csup\u003e1\u003c/sup\u003e\n`resize_to_limit`|`width`, `height`|`width`, `height`|`width`, `height`\n`resize_to_fit`|`width`, `height`|`width`, `height`|`width`, `height`\n`resize_to_fill`|`width`, `height`, `gravity`\u003csup\u003e2\u003c/sup\u003e|`width`, `height`, `gravity`\u003csup\u003e2\u003c/sup\u003e|`width`, `height`\n`resize_and_pad`|`width`, `height`, `background`, `gravity`\u003csup\u003e2\u003c/sup\u003e|`width`, `height`, `background`, `gravity`\u003csup\u003e2\u003c/sup\u003e|`width`, `height`, `background`, `gravity`\u003csup\u003e2\u003c/sup\u003e\n`resize_to_geometry_string`|`geometry_string`\u003csup\u003e3\u003c/sup\u003e|*not implemented*|*not implemented*\n`crop`|`left`, `top`, `width`, `height`|`left`, `top`, `width`, `height`|`left`, `top`, `width`, `height`\n\n\u003csup\u003e1\u003c/sup\u003e`page` refers to the page number when converting from PDF, frame number when converting from GIF, and layer number when converting from PSD.\n\n\u003csup\u003e2\u003c/sup\u003e`gravity` refers to an image position given as one of `Center`, `North`, `NorthWest`, `West`, `SouthWest`, `South`, `SouthEast`, `East`, or `NorthEast`.\n\n\u003csup\u003e3\u003c/sup\u003e`geometry_string` is an [ImageMagick geometry string](https://rmagick.github.io/imusage.html#geometry).\n\n## Migrating from Paperclip\n\nIf you are using Paperclip, you can use the provided compatibility module:\n\n```ruby\nclass AvatarUploader \u003c CarrierWave::Uploader::Base\n  include CarrierWave::Compatibility::Paperclip\nend\n```\n\nSee the documentation for `CarrierWave::Compatibility::Paperclip` for more\ndetails.\n\nBe sure to use mount_on to specify the correct column:\n\n```ruby\nmount_uploader :avatar, AvatarUploader, mount_on: :avatar_file_name\n```\n\n## I18n\n\nThe Active Record validations use the Rails `i18n` framework. Add these keys to\nyour translations file:\n\n```yaml\nerrors:\n  messages:\n    carrierwave_processing_error: failed to be processed\n    carrierwave_integrity_error: is not of an allowed file type\n    carrierwave_download_error: could not be downloaded\n    extension_allowlist_error: \"You are not allowed to upload %{extension} files, allowed types: %{allowed_types}\"\n    extension_denylist_error: \"You are not allowed to upload %{extension} files, prohibited types: %{prohibited_types}\"\n    content_type_allowlist_error: \"You are not allowed to upload %{content_type} files, allowed types: %{allowed_types}\"\n    content_type_denylist_error: \"You are not allowed to upload %{content_type} files\"\n    processing_error: \"Failed to manipulate, maybe it is not an image?\"\n    min_size_error: \"File size should be greater than %{min_size}\"\n    max_size_error: \"File size should be less than %{max_size}\"\n    min_width_error: \"Image width should be greater than %{min_width}px\"\n    max_width_error: \"Image width should be less than %{max_width}px\"\n    min_height_error: \"Image height should be greater than %{min_height}px\"\n    max_height_error: \"Image height should be less than %{max_height}px\"\n```\n\nThe [`carrierwave-i18n`](https://github.com/carrierwaveuploader/carrierwave-i18n)\nlibrary adds support for additional locales.\n\n## Large files\n\nBy default, CarrierWave copies an uploaded file twice, first copying the file into the cache, then\ncopying the file into the store.  For large files, this can be prohibitively time consuming.\n\nYou may change this behavior by overriding either or both of the `move_to_cache` and\n`move_to_store` methods:\n\n```ruby\nclass MyUploader \u003c CarrierWave::Uploader::Base\n  def move_to_cache\n    true\n  end\n\n  def move_to_store\n    true\n  end\nend\n```\n\nWhen the `move_to_cache` and/or `move_to_store` methods return true, files will be moved (instead of copied) to the cache and store respectively.\n\nThis has only been tested with the local filesystem store.\n\n## Skipping ActiveRecord callbacks\n\nBy default, mounting an uploader into an ActiveRecord model will add a few\ncallbacks. For example, this code:\n\n```ruby\nclass User\n  mount_uploader :avatar, AvatarUploader\nend\n```\n\nWill add these callbacks:\n\n```ruby\nbefore_save :write_avatar_identifier\nafter_save :store_previous_changes_for_avatar\nafter_commit :remove_avatar!, on: :destroy\nafter_commit :mark_remove_avatar_false, on: :update\nafter_commit :remove_previously_stored_avatar, on: :update\nafter_commit :store_avatar!, on: [:create, :update]\n```\n\nIf you want to skip any of these callbacks (eg. you want to keep the existing\navatar, even after uploading a new one), you can use ActiveRecord’s\n`skip_callback` method.\n\n```ruby\nclass User\n  mount_uploader :avatar, AvatarUploader\n  skip_callback :commit, :after, :remove_previously_stored_avatar\nend\n```\n\n## Uploader Callbacks\n\nIn addition to the ActiveRecord callbacks described above, uploaders also have callbacks.\n\n```ruby\nclass MyUploader \u003c ::CarrierWave::Uploader::Base\n  before :remove, :log_removal\n  private\n  def log_removal\n    ::Rails.logger.info(format('Deleting file on S3: %s', @file))\n  end\nend\n```\n\nUploader callbacks can be `before` or `after` the following events:\n\n```\ncache\nprocess\nremove\nretrieve_from_cache\nretrieve_from_store\nstore\n```\n\n## Contributing to CarrierWave\n\nSee [CONTRIBUTING.md](https://github.com/carrierwaveuploader/carrierwave/blob/master/CONTRIBUTING.md)\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2008 Jonas Nicklas\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n","funding_links":[],"categories":["Ruby","File Uploading","Uncategorized","File Upload","File uploaders","Gems","文件上传"],"sub_categories":["Omniauth","Uncategorized","File Upload","Articles","Rails"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarrierwaveuploader%2Fcarrierwave","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcarrierwaveuploader%2Fcarrierwave","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarrierwaveuploader%2Fcarrierwave/lists"}