How can I restrict Paperclip to only accept images? I'm using Amazon S3 for storage if that's relevant. Thanks for reading.
Asked
Active
Viewed 7,952 times
13
-
3Moonpatrol's got a wicked answer for this. I'd accept his answer for newcomers. – Joshua Pinter Apr 14 '12 at 21:50
2 Answers
25
From https://makandracards.com/makandra/606-only-allow-pictures-as-paperclip-attachments
validates_attachment_content_type :image, :content_type => /^image\/(jpg|jpeg|pjpeg|png|x-png|gif)$/, :message => 'file type is not allowed (only jpeg/png/gif images)'

moonpatrol
- 1,202
- 11
- 15
-
3For Rails 4, the regex should be `/\Aimage\/(jpg|jpeg|pjpeg|png|x-png|gif)\z/`. – zsalzbank May 13 '14 at 21:51
-
How would I write it if I only wanted to restrict to .csv files? validates_attachment_content_type :csv, :content_type => /^csv\/(csv)$/, :message => 'file type is not allowed (only csv files)' – Jubl May 30 '16 at 03:55
13
Paperclip has validation methods like validates_attachment_presence
, validates_attachment_content_type
, and validates_attachment_size
.
So all you need to do is pass mime types of images you'd like to have as attachments:
validates_attachment_content_type 'image/png', 'image/jpg'

Eimantas
- 48,927
- 17
- 132
- 168
-
Thanks for your help. Regarding this from the rdoc: "It should be noted that Internet Explorer upload files with content_types that you may not expect. For example, JPEG images are given image/pjpeg and PNGs are image/x-png, so keep that in mind when determining how you match. Allows all by default. ", is there a standard list I can use that will allow all images in all browsers? – ben Jan 13 '11 at 05:07
-
1Not that i know of. You can try using wildcard like `image/*` but i'm not sure if paperclip supports that. – Eimantas Jan 13 '11 at 05:26
-
3The content_type "can be a String or a Regexp" according to the RDoc here http://rdoc.info/gems/paperclip/2.3.8/Paperclip/ClassMethods:validates_attachment_content_type – Lorenz Feb 24 '11 at 11:16
-