Paperclip中的样式仅适用于图片 [rails]

9

我正在使用Paperclip来上传各种文件(文本文档、二进制文件、图像)。

我想把它放在我的模型中:

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

但是它只有在图片的情况下才需要执行样式。我尝试添加

,但这会导致HTML代码错误。
if :attachment_content_type =~ /^image/

但是它没有起作用。
3个回答

16
你可以使用before_<attachment>_post_process回调函数来停止非图片的缩略图生成。如果在回调函数中返回false,则不会尝试使用样式。
请参阅文档中的 "事件" 部分。
  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 

3
也许你需要类似这样的东西:
:styles => lambda { |attachment| 
    !attachment.instance.image? ? {} : {:thumb => "80x24", :preview => "800x600>"} 
}

在您的模型中定义方法:

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

1

你可以在你的模型上使用

    `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"`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接