I am available for freelance work! Click here to email me.

Paperclip: Attaching Files in Rails

April 17th, 2008

Edit: Added paperclip validations

Paperclip is an awesome rails plugin by Jon Yurek at Thoughtbot. It is one of many plugins currently available that cater for file uploading and thumbnailing (see: Attachment_fu, file_column, etc). Now a quick quote from Jon:

For some reason, file attachment is annoying. I donít know why, and I know a lot of people have attempted to solve the problem in the past, myself included. Yet it still is. Having gotten fed up with gotchas and design decisions that we didnít agree with, I went and wrote Paperclip on the plane to RailsConf last year. Weíve been using it here in various forms since and IMHO itís the way to handle uploads, and finally decided that it should be released.

Installing Paperclip

You can install Paperclip using a variety of different methods:

svn export https://svn.thoughtbot.com/plugins/paperclip/tags/rel_2-0-2
piston import https://svn.thoughtbot.com/plugins/paperclip/trunk

You can also grab Paperclip from the git repository.

Quick Note: If you’re a windows user, you’re going to need to go for the trunk version as this contains a fix to a problem that basically meant that Paperclip borked.

Basic Usage

class User < ActiveRecord::Base
  # Paperclip
  has_attached_file :photo,
    :styles => {
      :thumb=> "100x100#",
      :small  => "150x150>" }
end

Attached files don’t need to have a seperare model (thank god). Your attachments are treated just like any other atribute. Images aren’t saved until your model is saved. There are a lot of bonus options but I’ll cover them towards the end of the article.

class AddPhotoToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :photo_file_name, :string # Original filename
    add_column :users, :photo_content_type, :string # Mime type
    add_column :users, :photo_file_size, :integer # File size in bytes
  end

  def self.down
    remove_column :users, :photo_file_name
    remove_column :users, :photo_content_type
    remove_column :users, :photo_file_size
  end
end

Don’t forget to add these columns! Otherwise you’ll end up scratching your head and wondering where the hell you went wrong. The first part of the column names is the same as whatever you’re called your attached file. In our case that’s photo. Now update your database:

rake db:migrate

Now that your database is sorted, we can start working on adding some content. In your view you can add a file field like you would normally:

<% form_for :user, :html => { :multipart => true } do |f| %>
  <%= f.file_field :photo%>
<% end %>

Don’t forget the :multipart => true part or everything will fail. Then you will cry.

Now in your controller, you don’t need to do a thing (hooray).

def create
  @user = User.create(params[:user])
end

You should now be able to upload user photos to your hearts content.

To display your user’s photos all you need to do is call:

<%= image_tag @user.photo.url %>
<%= image_tag @user.photo.url(:thumb) %>

The first call will display the original image. The second one will display the thumbnail image. Easy, yes?

Paperclip Validations

At the moment Paperclip has two different validation types, validates_attachment_presence and validates_attachment_content_type.

validates_attachment_presence

validates_attachment_presence gives your ActiveRecord style validations to check to see if your paperclip model has an attachment present.

validates_attachment_presence :avatar
validates_attachment_content_type

validates_attachment_content_type lets your check the type of file that has been uploaded by checking it’s mime type.

validates_attachment_content_type :avatar, :content_type => 'image/jpeg'

Paperclip Options

Now that you’ve seen how easy to use and awesome Paperclip is, let’s have a look at some of the additional settings you can use:

has_attached_file :photo, :url => "/:class/:attachment/:id/:style_:basename.:extension"

Using :url you set when your images can be accessed from. The above setting would mean that your files are located at URLs similiar to /user/photo/1/thumb_originalfilename.jpg”

has_attached_file :photo, :default_url => "/:class/:attachment/missing_:style.png"

The :default_url option is used if there is no attached file for a model. If a user doesn’t have any uploaded avatar you could use this option to set a default avatar to show.

has_attached_file :photo, :styles => { :normal => "100x100#", :small => ["70x70>", :jpg] }

:styles is a hash of thumbnail styles. The styles use the standard ImageMagick geometry rules. Paperclip also adds the ‘#’ option which will create square thumbnails that are nicely cropped.

has_attached_file :photo, :default_style => :thumb

:default_style is pretty straight forward. You can select a default style from your style list that will be called, instead of the original file, when you use @user.photo.url

has_attached_file :photo, :path => ":rails_root/public/:class/:attachment/:id/:style_:basename.:extension"

Using :path you can select where the files are saved to on your box. If you change this, make sure to change the :url setting to relate to the new path.

has_attached_file :photo, :whiny_thumbnails => true

:whiny_thumbnails will raise an error if there is a problem creating thumbnails. Set to true by default.

Some Waffle

Paperclip is a great plugin. It has a smaller memory footprint than Attachment_fu, it doesn’t require the use of Rmagick (eugh) and it has all the options that I’ve wished that Attachment_fu had. Give it a try and let me know what you think

Again, maximum kudos to Jon Yurek and all the guys over at ThoughtBot.

(Possibly) Related Posts

Recommend Me

If you found this post or anything else on this site of any use, then please take the time to recommend me on Working with Rails.

You can follow any responses to this entry through the RSS 2.0 feed. Trackback from your own site.

  • Guest
    that's awesome
  • Fun_register
    This is Wonderful plugin. Easy and nice to use it...I love very much
  • Tam
    Would it be possible to have paperclip only check for an image upload on a specific action? The usual model validation code is something like:

    validates_presence_of :first_name, :on => "update"
  • David
    can you use paperclip to upload and play videos? help please?
  • thinktogether
    Thaks for tutorial
  • jbeginsamuel
    Hi,

    I have uploaded a Image with begin.samuel.jpg. Then I have uploaded different image with the same name begin.samuel.jpg. Why it was overwriting the existing image . It should create a new image or versioning the existing image right. Is it limitation of Paper clip. Anybody come a cross scenario like this.

    I need your help.
  • madelein
    I have a problem on my emails.There are paperclips attachments what will not open
  • sharkfin
    @Dennis: Set the path and url options to something like:

    :path => ":rails_root/public/static/images/:class/:attachment/:id_:style.:extension",
    :url => "/static/images/:class/:attachment/:id_:style.:extension"

    Note: the id is used as part of the fie name not a directory.
  • M Rashid
    I am using Paperclip plugin for files upload. Can anybody help me how i rename uploaded file using Paperclip
  • snot
    I couldn't get this to work. it seemed that nothing got uploaded. The problem was that I hadn't added :photo to my attr_accessible list in my user model... otherwise great tutorial :)
  • RashOnRails
    Thanks! After days of deepening the indentation on my office wall (from where I had been banging my head) I finally have a simple image upload solution that works in my Windows dev environment. Bless you.
  • Tim
    Hi, you got it to work on windows? any mods?
  • Zoran Kikic
    You can set compression quality like this:

    has_attached_file :attachment1,
    :styles => { :thumb => [...],
    :convert_options => { :thumb => '-quality 96', :all => 'strip', ... }
    ...
  • here is the git diff for the changes I made for the quality:



    diff --git a/lib/paperclip/thumbnail.rb b/lib/paperclip/thumbnail.rb
    index 2178a9c..229317e 100644
    --- a/lib/paperclip/thumbnail.rb
    +++ b/lib/paperclip/thumbnail.rb
    @@ -2,7 +2,7 @@ module Paperclip
    # Handles thumbnailing images that are uploaded.
    class Thumbnail < Processor

    - attr_accessor :current_geometry, :target_geometry, :format, :whiny, :convert_options
    + attr_accessor :current_geometry, :target_geometry, :format, :whiny, :convert_options, :quality

    # Creates a Thumbnail object set to work on the +file+ given. It
    # will attempt to transform the image into one defined by +target_geometry+
    @@ -20,6 +20,7 @@ module Paperclip
    @convert_options = options[:convert_options]
    @whiny = options[:whiny].nil? ? true : options[:whiny]
    @format = options[:format]
    + @quality = 96

    @current_format = File.extname(@file.path)
    @basename = File.basename(@file.path, @current_format)
    @@ -62,6 +63,7 @@ module Paperclip
    def transformation_command
    scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
    trans = "-resize \"#{scale}\""
    + trans << " -quality #{@quality}"
    trans << " -crop \"#{crop}\" +repage" if crop
    trans << " #{convert_options}" if convert_options?
    trans
  • It is very important to change the quality of the thumbnail.
    The default quality of imagemagick is 85.
    For me 85 is way too low, make the images look blur. I always go for 94-96

    When I was looking at the code, it accepts convert_options option and insert it into the convert command, but it does not work.

    The convert command take the option -quality value JPEG/MIFF/PNG compression level
    here is the detail: http://www.imagemagick.org/script/command-line-options.php#quality

    below line 65 of lib/paperclip/thumbnail.rb
    you can change to this:


    trans = "-resize \"#{scale}\""
    trans << " -quality 95"
    trans << " -crop \"#{crop}\" +repage" if crop


    I know it's ugly patching,
    but well... im a lazy boy.


    and THANKS for this Awesome plugin !!!
  • kevin
    thanks for the tutorial, how can i upload more than 1 image to a model?
  • Cooper
    Hi, how you use codebox to display the codes? are you using wordpress?
  • Hi,

    Paperclip is my new love.

    EXCEPT. Is there a way to have default urls for each individual style?

    I need a default thumb url as well as a default normal URL.... any ideas?

    Anyone done this before? Many thanks!!

    Ada
  • manish nautiyal
    Hi
    I am using paperclip for uploading only [gif & jpeg] files. Now I rename a doc file to gif and i upload it. It uploaded but it will be give error when i show it. Only original file uploaded no tiny and no thumb image is uploaded.

    Pls help to remove this error.
  • Re: Multiple attachments of the same type on one model:

    Simply created additional database fields for the various attachments you want. For example...

    t.string :image_1_file_name, :image_1_content_type
    t.string :image_2_file_name, :image_2_content_type
    t.string :image_3_file_name, :image_3_content_type
    t.string :billboard_file_name, :billboard_content_type
    t.integer :image_1_file_size, :image_2_file_size, :image_3_file_size, :billboard_file_size

    And your model...

    has_attached_file :image_1
    has_attached_file :image_2
    has_attached_file :image_3
    has_attached_file :billboard
  • marcus
    now it resizes, but only the thumb style

    :styles => { :thumb=> "20x20",:small => "10x10"},

    the small one is not created...
  • marcus
    hello, im using paperclip with windows
    but it doesnt resize any image
  • Jerome
    To delete the attachment, just set it to nil !

    @person.update_attribute(:picture, nil)
  • Craig
    I had to update the thumbnail.rb file at line 69 for people who upload CMYK JPG images:

    trans = "-colorspace RGB -resize \"#{scale}\""
  • I don't want the original image beacuse i haven't many space. is possible resize it or delete it?
    thanks
  • Kumar
    Hi Jim,

    Nice writeup, I have recently started using Paperclip and it is simply gr8 to work with.

    I have a small query and any of the Gurus can answer this. In one of my project requirement I have to generate round thumbnails, I tried using many options, but I am not able to generate one, I used the :convert_options to pass the command line options to generate the thumbnails but to no avail. Any help on this will be greatly helpful.

    Thanks in Advance,
    Kumar
  • @Yves: I think file_column keep the temporar file when the validation fails. Would be nice see it in paperclip.
  • Dennis
    If I have over 1,000,000 users in my database and they all have an avatar using Paperclip I would end up with an avatar-folder with 1,000,000 subfolders (which my ext3 filesystem probably won't handle very well).
    Attachment_fu splits the id's up into subfolders (preventing more than 1000 entries in each folder).

    How does Paperclip handle this for large models?
  • Ted
    Is anyone able to upload a non-image file with Paperclip? If so, how is the link created (in the view file) for the uploaded (non-image) file? The docs appear to address only image files.
  • Yves
    One more thingÖ I haven't seen a Fileupload plugin which is capable of keeping the temporar file of an upload if the validation fails.

    For instance we've the model Medium which has_attachment :file and validates_presence_of :comment. If we left out the comment but specified a :file (let's say a big one... 200MB...) the validation will fail and the data is lost.
    It's pretty annoying if you have to upload the file again.

    As a workaround you can reflect the validation on client side... but it's not a solution for the problem.
  • Yves
    The problem above (caused by passenger) could be solved. Either as told in comment 53 on http://railscasts.com/episodes/134-paperclip#comments or by setting PATH as environment variable for Mac OS X 10.5 in /System/Library/LaunchDaemons/org.apache.httpd.plist:

    http://gist.github.com/28112
  • michael
    Does this work with word documents as well?
  • m3talsmith
    Just a note. For some reason I needed to add :imageName_updated_at (where imageName is what you are naming your avatar or whatever) to my columns in my model. This is in addition to the other 3 columns added. Just a heads up for those who may bump into this issue.
  • Yves
    Hi,

    me againÖ I'm on Mac OS X 10.5 running the latest version of Passenger with Ruby and Apache shipped with Mac OS.
    ImageMagick is working fine on the commandline ñ but uploading a file fails with

    "/tmp/stream.56928.1 is not recognized by the 'identify' command."

    I tried reinstalling ImageMagick from MacPorts without any success related to this problem.
  • @Yves - You can use interpolations. Check out this article for more info
  • Yves
    Hi,

    is there a way to get associations work in :path parameter?

    class Medium ":rails_root/upload/:project_id/:class/:id/:style/:basename.:extension"


    I'd like to group my files by the associated project_id - but it currently just makes an "/project_id" out of the pattern
  • mjjjhjemj
    I want to add UUID's to the filename and upload these to S3. I have
    figured out the configurations to implement S3, but am struggling a
    bit to figure out where to make the change so the UUID is included as
    part of the filename stored in S3 and in the photos table. Could you
    help point me where to make the changes?

    Any help is greatly appreciated,
    Mike
  • remco: You could either do

    has_attached_file :image1
    has_attached_file :image2

    and so on eight times, or make a separate Image model with something like

    has_attached_file :image
    belongs_to :user
  • remco
    Hi,

    I want to add 8 different images to the user. Is this possibly in paperclip?

    Grtz..remco
  • I think it would be worthwhile explaining what the # and > in the styles mean.
  • Kelly
    Nevermind. I ran through the super-handy-guide step by step again, restarted the system, and now everything works.
  • Kelly
    Awesome post, Jim.
    I had it up and running in 10 minutes, however, the style attributes fail to generate. Maybe you or someone else here can help a fellow Rails noob?

    My Product model has:
    has_attached_file :image, :styles => { :small => "150x150>", :thumb => '100x100>'}

    My Show view has:


    All I get is a broken image link because it's looking for the image in the path:
    "/images/14/small/IMG_0014.JPG?1226018755"

    which doesn't exist. I take the :small argument out and it produces the original photo that was uploaded and saved to:
    /public/images/14/original/...

    My output via the console is:
    ActionController::RoutingError (No route matches "/images/14/small/IMG_0014.JPG" with {:method=>:get})

    Is it supposed to generate the /small directory on save? I have ImageMagick installed by following the instructions here:
    http://socialcoop.wordpress.com/2008/09/18/super-handy-guide-for-installing-imagemagick-on-mac-os-x-1054/

    I appreciate anyone's help on this one! Thanks!
  • Thanks Jim!
  • Eduardo
    Is there a way to define more than one default image through ":default" parameter ? I would like to set a "female" image style do female users and "male" image style to male users.

    Thanks
  • Eduardo
    Bye bye Attachment_fu.
  • @paul - Paperclip can use s3 if needed.
  • Great write-up! Just one thing holding me back... it looks like there is no integration with Amazon S3 is that true or is it coming in a future release? Anyone know. I'll use this on some client projects for sure (they don't need S3 for storage).

    Thanks!
  • arash
    anyone know how to use paperclip from a migration to do batch image uploading?
  • I'm having the same problem as Hutch. It's definitely linked to Paperclip, as uninstalling it makes the problem go away. Any ideas anyone? I, too, have nothing coming up in my logs. Hutch, are you using mod_rails?
  • @george - Have you set the form to use :multipart => true?
  • george
    Hi Thanks for the plugin,
    What is the name of the folder that paperclip saves the file?
    i created all the steps outline above and even installed image magic , am running rails 2.1.1 on ubuntu linux hardy 8.04.1 with ruby 1.8.6

    It seems that nothing is getting uploaded.
  • Kevin Monk
    Well well done Jon Yurek then and well done to you for bringing it to people's attention.

    I'm just playing around with it at the moment but I'm having quite a bit of success with it.

    I'm having a couple of issues with it though; once I've uploaded an image with paperclip, I'm trying to modify it and save it to a separate model. THe image manipulation could be done with ImageMagick but saving the modified image back as an attachment is proving quite difficult.

    If you can imagine an app similar to the Mii characters on the Wii console. THat's kind of what I'm trying to achieve. Upload body parts images and then create a new image based on the original uploaded images. If anybody has any thoughts about how an app like this might be achieved then I'd love to hear fom you.
  • @Kevin Monk - I didn't create the plugin. All kudos should be aimed towards Jon Yurek and the guys at Thoughtbot.com
  • Kevin Monk
    This plugin has been extremely useful for me. Thanks for creating it.
  • So I'm having a strange problem that I've yet to see anyone else mention. Every now and again, maybe one in ten page loads, the page just... won't finish loading. It'll stop and you'll be left with a white, blank page. Try it yourself:

    http://www.thescrabbled.com

    I checked the logs and there's no errors... it just stops halfway through all the [paperclip] lines. Anyone have any similar experiences or know why this might be happening? I have no direct evidence that it's paperclip's fault, only that it just started doing this immediately after adding paperclip icons.
  • Mark
    Has anyone encountered a problem with the validates_attachment_content_type when validating for a csv file?
    it seems that safari and possibly other browsers don't send what paperclip expects in the headers and content_type is blank, however when using firefox it all works jolly good.
    here's the validation line I'm using:
    validates_attachment_content_type :import, :content_type => ["text/csv"], :message => "only accepting .csv files at the moment"

    I've tried adding other strings to the valid type array, "text", "text/file" but I'm pretty sure it's comparing those to a blank entry when the request comes from Safari.
  • Greg
    Another gotcha: Be sure to include the ":photo" (or whatever your paperclip object) to your attr_accessible list if you are using attr_accessible to control access to attributes. I was having trouble getting files to save until I noticed the error message in my log of "Can't mass-assign these protected attributes: photo".

    Some searching found this reference: http://tinyurl.com/5vem2n

    Kevin's comments were very helpful in getting the edit to work. Thanks, Kevin, Jim, and Jon.
  • Hi Hugues,

    Did you call has_attached_file before the validations. The has_attached_file method is what attaches the paperclip validations to the model.
  • Good tutorial.Thanks.
    My only concerns so far is about validations.
    I get a NoMethodError when I use validates_attachment_content_type :photo, :content_type => 'image/jpeg' inside the user.rb model.
    I'll have to work on that later but if someone can point me out some hints, that would be nice.
  • Kevin
    resolved my own issue.

    edit controller remained unchanged from restful scaffolding, all I did was adjust the attributes of the form_for tag on my edit view:

    where the form for on my new view was:

    posts_path, :html => { :multipart => true } do |f| %>

    the form_for on my edit view became:

    post_path, :action => 'update', :html => { :multipart => true, :method => :put } do |f| %>

    I confess this was part trial and error, but it works flawlessly, even with multiple attachments.
  • Kevin
    I'd love it if someone could point me towards an edit/update controller action. Jon has said elsewhere that this will require a slightly modified or special action (ie not RESTful) to keep the file that's currently attached to the record (if you're not attaching a new one). As it stands, clicking 'update' in my edit view just spawns a new record, which is kind of unexpected.

    Please help!
  • foo
    You say "For some reason, file attachment is annoying."
    For some reason, testing file attachments is also annoying.
    Got some examples (preferable rspec) of both model and controller specs?
  • Hi,

    I installed paperclip and its uploading the files correctly but is not generating the thumbnails. I read somewhere that they are not generated by default. What can i do so paperclip start generating the thumbnails?
  • Rex
    We've added some patch to paperclip for checking content type before trying to create a thumbnail. When the file is a pdf, imagemagick tries to make thumbnails of everypage, making it very slow.

    http://devblog.rorcraft.com/2008/8/1/patching-paperclip-to-only-thumbnail-images
  • kasey
    anyone know how to change the basename of a file before it gets stored? i want to append some unique identifiers onto the file so we dont get naming conflicts....
  • Jonathan
    Is it possible to not store the original file?

    How would you go about it?
  • Glenn Powell
    I use this plugin and it is wonderful. Make sure you stay up to date with the versions in GIT though. There were quite a few important updates yesterday.

    One question for anyone who may know of a smart solution. I've looked through the docs and code, but can't find any way to define a Max file size to ensure a user doesn't upload a 3000x3000 BMP which would then get stored in the /original subdirectory. Can you simply supply the :styles option with an :original field? hm, maybe I'll try that. Anyways, great plugin.
  • Dan
    Looks cool, but I'm on a windows machine. What is the fix I need, and how do I install the trunk version. Anyone have any more details?
  • Very nice tutorial !! But maybe you can help me.. how can i delete/destroy the files? I want to use the uploads as backgrounds for a template on websites. People can edit this, so -after changing the background for 5 times- i have 5 different files, when i'm using only one.

    Is this possible with paperclip, or do i have to write some extra code?
  • @Roob - I've had the same problem with IE before.

    Down with IE.
  • @roob @admin
    maybe you'll get some trouble also from png images (internet explorer mime type is "image/x-png")

    regards
    giovanni
  • Roob
    correction: internet explorer sends the mime-type "image/pjpeg" instead of "image/jpeg" with jpeg files. this is horrible, but if you validate for the additional mime-type, it works!
  • Roob
    it seems that the paperclip validates_attachment_content_type function has problems with files uploaded by internet explorer 7 (didn't test ie6). maybe the cause is the scrambled filename (whole path) that ie submits with the input type="file"?
  • Dios
    Is there any way to control compression quality of jpegs?
  • andy
    Thanks for this tutorial Jim, its been a real help. I have got paperclip working with swfupload, and all is great.

    I am wondering though if paperclip is suppose to manage the removal of files when the item is deleted/destroyed? or do i have to handle that my self?
  • johnny
    Just wanted to say that paperclip is awesome! I just used it to upload pdfs. Worked fine. Thanks for the pointers Jim!
  • David C
    Re: Attaching several images
    Do with seperate model

    AttachemntModel
    has_attached_file :photo, :styles => { :thumb=> "100x100#", :small => "150x150>" }
    belongs_to: post

    PostModel
    has_many: attachments
  • I can see this plugin blowing attachment_fu out of the water!
  • Wow, this is great, thanks :-)

    Just want to let people know about one gotcha that I found while trying to get avatars uploaded with my User model.

    Especially if you're using a plugin like restful_authentication, you have make sure that the avatar attribute is allowed to be mass-assigned:
    attr_accessible :avatar #or whatever your calling the attachment
    otherwise it won't allow you do update it via mass-assignment.
  • Sam
    Nice writeup. One of my favourite parts is "Donít forget the :multipart => true part or everything will fail. Then you will cry." ;)
  • Guest
    thanks for your article, this has helped a lot.

    but i have one question:
    would it be possible to provide paperclip just with a url to an image and it will download and store the picture in my filesystem?
  • Hi Jonas,

    I didn't actually write the Paperclip plugin, although I am an avid user. It was written by Jon Yurek from Thoughtbot.

    When I first started using Rails, I used to use file_column but I stopped using it for some reason I can't remember. I've not had a look at upload column yet, but will look into it.

    - Jim
  • Jonas Nicklas
    Good work, it looks pretty solid :) Though of course, as the author of a file uploading plugin myself (http://uploadcolumn.rubyforge.org), I have to wonder why you looked at file_column (which hasn't been maintained for years) and if you had a look at UploadColumn at all? UC and Paperclip seem very similar to me, so I'm wondering if there were any issues you had that made you decide to write your own plugin, so that those could possibly be fixed.
  • t3i
    Hi, i'm wondering what happens when records are updated. It seems to be setting all the attributes to NULL, is there a way to make it not change the photo attributes unless something is posted?
  • RubyPimp
    I love you!!!!!!
  • Looks fantastic, it's just a pity that it allows only one instance per file type... loses some usefulness that way.

    Good work!
  • Dios
    How do I change the DPI setting. I want it at 72 dpi, but it seems to default to 350 dpi for jpeg. Any way to control size/quality?
  • @tripurari - If you run the migrations shown above then Paperclip should automatically add those details to your database

    @Jeff - Not had that problem myself. Try reporting to the guy sat Thoughtbot.

    @Dominik Weiss - I don't think the validations were present when I originally wrote this. Noticed them myself today, so I've updated the article. Thanks for the heads up.

    @John Shamstonge - Paperclip is okay to use with any kind of file you want to attach to a model. Make sure you validate the file with validates_attachment_content_type though.
  • John Shamstonge
    Hey there,

    Does anyonek now if Paperclip is OK to use for non-image files?
  • Paperclip is awesome! Thanks for this little introdution :-)

    Anyway, I just wanted to add how to validate the content_type of the the upload:

    app/models/user.rb:
    validates_attachment_content_type(:image, { :content_type => ['image/jpg', 'image/jpeg', 'image/gif', 'image/png'] })
    validates_attachment_presence(:image)
  • Jeff
    When I also use validate_attachment_presence, paperclip saves null into the database. this seems to be a bug.
  • How to store the original file name,type of file and size of file in the databse using paperclip


    plz is there any one then help me
  • Is there a way to incorporate this with acts_as_commentable?

    I added has_attached_file to the comment.rb in the vendor/plugins dir and followed directions but its not saving the file. It keeps coming up blank.
  • Ben
    Ignore my comment above, I didn't really think that through all the way. I think what I will do is create an Attachment or Bucket Model, attach things to this model and create some special syntax to be able to link or embed them in posts.
  • Ben
    I am having a hard time finding a real world usage for this other than your 'avatar' examples. More common that wanting an avatar for a user profile is the ability to attach images to a blog post for example. Being that I couldn't have more than one image per post - it makes the whole thing pretty useless. Correct me if I am wrong (and I hope I am.) But this just seems to me like a glorified way to add images to a user profile.
  • Asis Hallab
    Dear Jim,

    yes, attaching multiple instances of the same file type is just what I want to do.
    Well, I'll try creating a wrapper like 'Attachment-Holder' and assign multiple instances of that wrapper. It's not truly the crown of coding, but it solves my problem for now. Don't you think?
  • @Kamran: I'm not entirely sure about the footprint comparisons using attachment_fu with an different image processor than ImageMagick. It would be interesting to see though

    @Asis Hallab: There's not an option to attach many files. Well, you can attach different files. You could have has_attached_file :photo and has_attached_file :doc or something, but I assume you mean attaching multiple instances of the same file type?
  • Asis Hallab
    Good day!

    I really dig Paper-Clip.
    I just have one question: Is there an option liek "has_many_attached_files", to assign many attachments to any ActiveRecord..

    Many tanks in advance!
  • Kamran
    Does this have a smaller memory footprint than attachment_fu+ImageScience, or attachment_fu+ImageMagick? Just wondering cause i just got through setting up all of that (with ImageScience), and i don't really see much here that is different other than not needing an extra model for the images, which i kinda like anyhow. It would be cool to add some other effects because you are using imagemagick, maybe some stuff like annotation, round corners, drop-shadows or grayscale and sepia.
  • Looks great, will plug this in on the next project for sure (not that attachment_fu is particularly horrible or anything). Good to keep finding fellow UK Rails people too, we just seem to keep popping up :)
  • admin
    @Harold: To quote Jon: "You just need ImageMagick installed somewhere".

    @Jon: I totally forgot about :filename not being used. I was just going through paperclip.rb to look at the options but :filename still appears in there.

    I've updated the post to use ":basename.:extension" now, and added the git repos.
  • Thanks for the good overview! I'm glad you like it.

    I should point out, though, that ":filename" isn't valid inside of the path and url options anymore. It should be ":basename.:extension". Also, the project is on git now for all so inclined.
  • Roob
    this is AWESOME! been searching for this quite awhile, especially because attachment_fu needs extra models for attachments. will try this asap.
  • Harold
    Hi!

    Nice work, this really takes the hassle of attachment_fu. Also I was wondering if PaperClips would work with ImageScience?

    Thanks!
blog comments powered by Disqus
Purify - Issue Tracker

Jim Neath is a 26 year old Freelance Ruby on Rails developer from Manchester, UK.

Recommend Me

Categories