如何限制Paperclip仅接受图像?

ben*_*ben 13 ruby-on-rails paperclip

如何限制Paperclip仅接受图像?如果相关,我正在使用Amazon S3进行存储.谢谢阅读.

moo*_*rol 26

来自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)'
Run Code Online (Sandbox Code Playgroud)

  • 对于Rails 4,正则表达式应该是`/\Aimage\/(jpg | jpeg | pjpeg | png | x-png | gif)\ z /`. (3认同)

Eim*_*tas 13

回形针已经验证方法,如validates_attachment_presence,validates_attachment_content_typevalidates_attachment_size.

所以你需要做的就是传递你想要作为附件的mime类型的图像:

validates_attachment_content_type 'image/png', 'image/jpg'
Run Code Online (Sandbox Code Playgroud)

  • 根据RDoc,content_type"可以是String或Regexp"http://rdoc.info/gems/paperclip/2.3.8/Paperclip/ClassMethods:validates_attachment_content_type (3认同)