13

How can I restrict Paperclip to only accept images? I'm using Amazon S3 for storage if that's relevant. Thanks for reading.

berkes
  • 26,996
  • 27
  • 115
  • 206
ben
  • 29,229
  • 42
  • 124
  • 179

2 Answers2

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
  • 3
    For 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
  • 1
    Not 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
  • 3
    The 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
  • are the parameters to validates_attachment_content_type correct? – jaydel Jan 30 '14 at 13:08