Paperclip的content_type根据应用程序无效,但不是

Cap*_*arl 4 ruby-on-rails paperclip ruby-on-rails-4

我是Paperclip的新手,这一切看起来都很快.我试图让用户只上传PNG或JPG,虽然我上传了一个JPG并且我的content_type验证了JPG但它仍然无效.

我已经尝试删除PNG content_type,但无济于事.

我尝试过使用过has_attached_file,但似乎忽略了:content_type和stuff.因为如果我:content_type => "image/png"只上传一个JPG ; 它没有给出错误.

有什么建议?

    validates_attachment :avatar, :styles => { 
                                    :medium => "300x300", 
                                    :thumb => "100x100" 
                                }, :content_type => { 
                                    :content_type => "image/jpg", 
                                    :content_type => "image/png"
                                },
                                :size => { :in => 0..1.megabytes }
Run Code Online (Sandbox Code Playgroud)

哦,当我在它的时候; 我想让我的拇指和中等到固定的宽度.所以没有缩放像100x80,但只有100x100.我怎样才能做到这一点?

Ric*_*eck 5

看起来你正试图使用​​一些Paperclip validation,你可以在这里看一下:Paperclip - 验证文件类型但不存在

根据那个答案,你可以使用这个:

validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3'], :if => :sound_attached?
Run Code Online (Sandbox Code Playgroud)

另一种方法是用来lambda检查您是否正在处理特定的内容类型.以下是我们的一个实时应用程序的示例:

   has_attached_file :attachment,
            styles:          lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"}  : {:thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10}, :medium => { :geometry => "300x300#", :format => 'jpg', :time => 10}}}

    def is_image?
            attachment.instance.attachment_content_type =~ %r(image)
    end
Run Code Online (Sandbox Code Playgroud)

Lambda只是衡量content-type你是否需要的一种方式(IE你只允许JPG图像).为了验证图像(而不是视频)的存在,您需要validates_attachment_content_type