Ruby on Rails: How do you check if a file is an image?

后端 未结 6 1806
醉酒成梦
醉酒成梦 2020-12-28 17:02

How would you check if a file is an image? I\'m thinking you could use an method like so:

def image?(file)
  file.to_s.include?(\".gif\") or file.to_s.includ         


        
6条回答
  •  时光说笑
    2020-12-28 17:43

    Since you're using Paperclip, you can use the built in "validates_attachment_content_type" method in the model where "has_attached_file" is used, and specify which file types you want to allow.

    Here's an example from an application where users upload an avatar for their profile:

    has_attached_file :avatar, 
                      :styles => { :thumb => "48x48#" },
                      :default_url => "/images/avatars/missing_avatar.png",
                      :default_style => :thumb
    
    validates_attachment_content_type :avatar, :content_type => ["image/jpeg", "image/pjpeg", "image/png", "image/x-png", "image/gif"]
    

    The documentation is here http://dev.thoughtbot.com/paperclip/classes/Paperclip/ClassMethods.html

提交回复
热议问题