Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

paperclip

> 编程语言
Open source

Easy file attachment management for ActiveRecord

115.5K stars0 likes2 views
WebsiteGitHub

About

Easy file attachment management for ActiveRecord

Paperclip

Deprecated

Paperclip is deprecated.

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.

Existing documentation

Documentation valid for master branch

Please check the documentation for the paperclip version you are using: https://github.com/thoughtbot/paperclip/releases


  • Requirements
    • Ruby and Rails
    • Image Processor
    • file
  • Installation
  • Quick Start
    • Models
    • Migrations
    • Edit and New Views
    • Edit and New Views with Simple Form
    • Controller
    • View Helpers
    • Checking a File Exists
    • Deleting an Attachment
  • Usage
  • Validations
  • Internationalization (I18n)
  • Security Validations
  • Defaults
  • Migrations
    • Add Attachment Column To A Table
    • Schema Definition
    • Vintage Syntax
  • Storage
    • Understanding Storage
  • IO Adapters
  • Post Processing
  • Custom Attachment Processors
  • Events
  • URI Obfuscation
  • Checksum / Fingerprint
  • File Preservation for Soft-Delete
  • Dynamic Configuration
    • Dynamic Styles:
    • Dynamic Processors:
  • Logging
  • Deployment
    • Attachment Styles
  • Testing
  • Contributing
  • License
  • About thoughtbot

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.


Requirements

Ruby and Rails

Paperclip now requires Ruby version >= 2.1 and Rails version >= 4.2 (only if you're going to use Paperclip with Ruby on Rails).

Image Processor

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):

ruby
Paperclip.options[:command_path] = "/usr/local/bin/"

If you're on Mac OS X, you'll want to run the following with Homebrew:

bash
brew install imagemagick

If 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:

bash
brew install gs

If you are on Ubuntu (or any Debian base Linux distribution), you'll want to run the following with apt-get:

bash
sudo apt-get install imagemagick -y

file

The 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 file from 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 works

OR

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 server

Either 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)


Installation

Paperclip is distributed as a gem, which is how it should be used in your app.

Include the gem in your Gemfile:

ruby
gem "paperclip", "~> 6.0.0"

Or, if you want to get the latest, you can get master from the main paperclip repository:

ruby
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:

ruby
class ModuleName < ActiveRecord::Base
  include Paperclip::Glue
  ...
end

Quick Start

Models

ruby
class 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/
end

Migrations

Assuming you have a users table, add an avatar column to the users table:

ruby
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)

Edit and New Views

Make sure you have corresponding methods in your controller:

erb
<%= form_for @user, url: users_path, html: { multipart: true } do |form| %>
  <%= form.file_field :avatar %>
  <%= form.submit %>
<% end %>

Edit and New Views with Simple Form

erb
<%= simple_form_for @user, url: users_path do |form| %>
  <%= form.input :avatar, as: :file %>
  <%= form.submit %>
<% end %>

Controller

ruby
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)
end

View Helpers

Add these to the view where you want your images displayed:

erb
<%= image_tag @user.avatar.url %>
<%= image_tag @user.avatar.url(:medium) %>
<%= image_tag @user.avatar.url(:thumb) %>

Checking a File Exists

There are two methods for checking if a file exists:

  • file? and present? checks if the _file_name field is populated
  • exists? 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.

Deleting an Attachment

Set the attribute to nil and save.

ruby
@user.avatar = nil
@user.save

Usage

The 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_at

By 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.

Validations

For validations, Paperclip introduces several validators to validate your attachment:

  • AttachmentContentTypeValidator
  • AttachmentPresenceValidator
  • AttachmentSizeValidator

Example Usage:

ruby
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_presence
  • validates_attachment_content_type
  • validates_attachment_size

Example Usage:

ruby
validates_attachment_presence :avatar

Lastly, you can also define multiple validations on a single attachment using validates_attachment:

ruby
validates_attachment :avatar, presence: true,
  content_type: "image/jpeg",
  size: { in: 0..10.kilobytes }

_NOTE: Post-processing will not even start if the

Issues· 53 open

View all issuesOpen on GitHub
  • #2708

    ContentTypeDetector false positive from Mime

    Updated Jul 5, 2023
  • #2709

    s3 deprecating TLS 1.1 and moving to default TLS 1.2

    Updated May 24, 2023
  • #2667

    Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

    Updated Apr 15, 2023
  • #2685

    Transfer ownership of gem to Kreeti

    Updated Dec 30, 2022
  • #2707

    use file -b --mime 'test.json' have problem in AWS linux 2

    Updated Nov 10, 2022
  • #2706

    Webp image upload issue

    Updated Nov 8, 2022
  • #2705

    *_file_name attribute without extension

    Updated Oct 18, 2022
  • #2673

    With Ruby 3.0 validator produces "ArgumentError: wrong number of arguments (given 3, expected 1..2)"

    Updated Sep 13, 2022
  • #2698

    "attachment" type migration error in Rails 7

    Updated Aug 12, 2022
  • #2678

    Paperclip mimemagic dependency licensing implication

    Updated Aug 10, 2022

> Tags

Ruby

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedNov 21, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言