Easy file attachment management for ActiveRecord
Easy file attachment management for ActiveRecord
For new projects, we recommend Rails' own ActiveStorage.
For existing projects, please consult and contribute to the migration guide, available in English, en español, and as a video recorded at RailsConf 2019. You may also prefer an alternative migration tutorial used by Doorkeeper.
Alternatively, for existing projects, Kreeti is maintaining kt-paperclip, an ongoing fork of Paperclip.
We will leave the Issues open as a discussion forum only. We do not guarantee a response from us in the Issues. All bug reports should go to kt-paperclip.
We are no longer accepting pull requests except pull requests against the migration guide. All other pull requests will be closed without merging.
master branchPlease check the documentation for the paperclip version you are using: https://github.com/thoughtbot/paperclip/releases
Paperclip is intended as an easy file attachment library for ActiveRecord. The intent behind it was to keep setup as easy as possible and to treat files as much like other attributes as possible. This means they aren't saved to their final locations on disk, nor are they deleted if set to nil, until ActiveRecord::Base#save is called. It manages validations based on size and presence, if required. It can transform its assigned image into thumbnails if needed, and the prerequisites are as simple as installing ImageMagick (which, for most modern Unix-based systems, is as easy as installing the right packages). Attached files are saved to the filesystem and referenced in the browser by an easily understandable specification, which has sensible and useful defaults.
See the documentation for has_attached_file in Paperclip::ClassMethods for
more detailed options.
The complete RDoc is online.
Paperclip now requires Ruby version >= 2.1 and Rails version >= 4.2 (only if you're going to use Paperclip with Ruby on Rails).
ImageMagick must be installed and Paperclip must have access to it. To ensure
that it does, on your command line, run which convert (one of the ImageMagick
utilities). This will give you the path where that utility is installed. For
example, it might return /usr/local/bin/convert.
Then, in your environment config file, let Paperclip know to look there by adding that directory to its path.
In development mode, you might add this line to config/environments/development.rb):
Paperclip.options[:command_path] = "/usr/local/bin/"If you're on Mac OS X, you'll want to run the following with Homebrew:
brew install imagemagickIf you are dealing with pdf uploads or running the test suite, you'll also need to install GhostScript. On Mac OS X, you can also install that using Homebrew:
brew install gsIf you are on Ubuntu (or any Debian base Linux distribution), you'll want to run the following with apt-get:
sudo apt-get install imagemagick -yfileThe Unix file command is required for content-type checking.
This utility isn't available in Windows, but comes bundled with Ruby Devkit,
so Windows users must make sure that the devkit is installed and added to the system PATH.
Manual Installation
If you're using Windows 7+ as a development environment, you may need to install the file.exe application manually. The file spoofing system in Paperclip 4+ relies on this; if you don't have it working, you'll receive Validation failed: Upload file has an extension that does not match its contents. errors.
To manually install, you should perform the following:
Download & install
filefrom this URL
To test, you can use the image below:
Next, you need to integrate with your environment - preferably through the PATH variable, or by changing your config/environments/development.rb file
PATH
1. Click "Start"
2. On "Computer", right-click and select "Properties"
3. In Properties, select "Advanced System Settings"
4. Click the "Environment Variables" button
5. Locate the "PATH" var - at the end, add the path to your newly installed `file.exe` (typically `C:\Program Files (x86)\GnuWin32\bin`)
6. Restart any CMD shells you have open & see if it worksOR
Environment
1. Open `config/environments/development.rb`
2. Add the following line: `Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'`
3. Restart your Rails serverEither of these methods will give your Rails setup access to the file.exe functionality, thus providing the ability to check the contents of a file (fixing the spoofing problem)
Paperclip is distributed as a gem, which is how it should be used in your app.
Include the gem in your Gemfile:
gem "paperclip", "~> 6.0.0"Or, if you want to get the latest, you can get master from the main paperclip repository:
gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git"If you're trying to use features that don't seem to be in the latest released gem, but are mentioned in this README, then you probably need to specify the master branch if you want to use them. This README is probably ahead of the latest released version if you're reading it on GitHub.
For Non-Rails usage:
class ModuleName < ActiveRecord::Base
include Paperclip::Glue
...
endclass User < ActiveRecord::Base
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
endAssuming you have a users table, add an avatar column to the users table:
class AddAvatarColumnsToUsers < ActiveRecord::Migration
def up
add_attachment :users, :avatar
end
def down
remove_attachment :users, :avatar
end
end(Or you can use the Rails migration generator: rails generate paperclip user avatar)
Make sure you have corresponding methods in your controller:
<%= form_for @user, url: users_path, html: { multipart: true } do |form| %>
<%= form.file_field :avatar %>
<%= form.submit %>
<% end %><%= simple_form_for @user, url: users_path do |form| %>
<%= form.input :avatar, as: :file %>
<%= form.submit %>
<% end %>def create
@user = User.create(user_params)
end
private
# Use strong_parameters for attribute whitelisting
# Be sure to update your create() and update() controller methods.
def user_params
params.require(:user).permit(:avatar)
endAdd these to the view where you want your images displayed:
<%= image_tag @user.avatar.url %>
<%= image_tag @user.avatar.url(:medium) %>
<%= image_tag @user.avatar.url(:thumb) %>There are two methods for checking if a file exists:
file? and present? checks if the _file_name field is populatedexists? checks if the file exists (will perform a TCP connection if stored in the cloud)Keep this in mind if you are checking if files are present in a loop. The first version is significantly more performant, but has different semantics.
Set the attribute to nil and save.
@user.avatar = nil
@user.saveThe basics of Paperclip are quite simple: Declare that your model has an
attachment with the has_attached_file method, and give it a name.
Paperclip will wrap up to four attributes (all prefixed with that attachment's name, so you can have multiple attachments per model if you wish) and give them a friendly front end. These attributes are:
<attachment>_file_name<attachment>_file_size<attachment>_content_type<attachment>_updated_atBy default, only <attachment>_file_name is required for Paperclip to operate.
You'll need to add <attachment>_content_type in case you want to use content type
validation.
More information about the options passed to has_attached_file is available in the
documentation of Paperclip::ClassMethods.
For validations, Paperclip introduces several validators to validate your attachment:
AttachmentContentTypeValidatorAttachmentPresenceValidatorAttachmentSizeValidatorExample Usage:
validates :avatar, attachment_presence: true
validates_with AttachmentPresenceValidator, attributes: :avatar
validates_with AttachmentSizeValidator, attributes: :avatar, less_than: 1.megabytes
Validators can also be defined using the old helper style:
validates_attachment_presencevalidates_attachment_content_typevalidates_attachment_sizeExample Usage:
validates_attachment_presence :avatarLastly, you can also define multiple validations on a single attachment using validates_attachment:
validates_attachment :avatar, presence: true,
content_type: "image/jpeg",
size: { in: 0..10.kilobytes }_NOTE: Post-processing will not even start if the
ContentTypeDetector false positive from Mime
s3 deprecating TLS 1.1 and moving to default TLS 1.2
Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:
Transfer ownership of gem to Kreeti
use file -b --mime 'test.json' have problem in AWS linux 2
Webp image upload issue
*_file_name attribute without extension
With Ruby 3.0 validator produces "ArgumentError: wrong number of arguments (given 3, expected 1..2)"
"attachment" type migration error in Rails 7
Paperclip mimemagic dependency licensing implication