简体   繁体   English

Paperclip中的样式只有在它是图像的情况下[rails]

[英]Styles in Paperclip only if it's an image [rails]

I'm using paperclip to upload all sorts of files (text documents, binaries, images). 我正在使用paperclip上传各种文件(文本文档,二进制文件,图像)。

I'd like to put this in my model: 我想把它放在我的模型中:

has_attached_file :attachment, :styles => { :medium => "300x300>", :thumb => "100x100>" }

but it has to perform the styles only if it's an image. 只有当它是一个图像时才必须执行这些样式。 I tried adding 我尝试添加

if :attachment_content_type =~ /^image/

but it didn't work. 但它不起作用。

You can use before_<attachment>_post_process callback to halt thumbnail generation for non-images. 您可以使用before_<attachment>_post_process回调来暂停非图像的缩略图生成。 If you return false in callback, there will be no attempts to use styles. 如果在回调中返回false ,则不会尝试使用样式。

See "Events" section in docs 请参阅文档中的 “事件”部分

  before_attachment_post_process :allow_only_images

  def allow_only_images
    if !(attachment.content_type =~ %r{^(image|(x-)?application)/(x-png|pjpeg|jpeg|jpg|png|gif)$})
      return false 
    end
  end 

May be you need something like this: 可能你需要这样的东西:

:styles => lambda { |attachment| 
    !attachment.instance.image? ? {} : {:thumb => "80x24", :preview => "800x600>"} 
}

And define method in your model: 并在您的模型中定义方法:

def image?
   attachment.content_type.index("image/") == 0
end

You can use on your model 您可以在您的模型上使用

    `has_attached_file :avatar,
      :styles => lambda { |a| if a.content_type =~ %r{^(image|(x-)?application)/(x-png|pjpeg|jpeg|jpg|png|gif)$}
                          { 
                            :thumb => "100x100#",
                            :medium => "300x300>",

                          }
                        else
                          Hash.new
                        end
                        },:default_url => "/missing.png"`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM