2009-07-30 38 views
13

我在Ruby on Rails上使用Paperclip将资源附加到模型,这些资源可以是任何文件类型,只有当资产是图像时才会生成当前缩略图。我希望能够为其他文件显示不同的默认图像,既可以通过上传文件生成缩略图,也可以使用default_url设置某些内容,但到目前为止我找不到任何资源来帮助完成此操作,我没有得到自己的位置。使用Paperclip为文件类型定制缩略图

我的模型如下:

class Asset < ActiveRecord::Base 
    has_attached_file :media, 
    :storage => :s3, 
    :s3_credentials => "#{RAILS_ROOT}/config/s3.yml", 
    :path => ":attachment/:id/:style.:extension", 
    :bucket => S3_BUCKET, 
    :styles => {:thumb => "75x75>", :large => "600x800>", 
    :whiny => false, 
    :default_url => "/images/:attachment/missing.jpg" 

没有人有生成自定义缩略图的任何资源,如果生成失败,或依傍是这样的:在默认网址CONTENT_TYPE?我已经查看了源代码,并且无法获取任何地方。

谢谢!

回答

17

我已经实现了这个非常相同的功能。回形针为我的所有图像和PDF生成缩略图,并且我为MS Word,Excel,HTML,TXT文件等添加了自定义缩略图图标。

我的解决方案非常简单。在我的模型Attachment(你的情况Asset)我已经定义了以下方法:

def thumbnail_uri(style = :original) 
    if style == :original || has_thumbnail? 
    attachment.s3.interface.get_link(attachment.s3_bucket.to_s, attachment.path(style), EXPIRES_AFTER) 
    else 
    generic_icon_path style 
    end 
end 

这将返回或者是URL存储在S3的缩略图,或基于内容的资产中的本地路径到一个通用的PNG图标类型(下面讨论)。 has_thumbnail?方法确定此资产是否有为其生成的缩略图。这是我在自己的Paperclip分支中添加的内容,但是您可以用自己的逻辑来替代(我不确定这种“标准”方式来确定此问题,可能会将路径与您定义的“缺失”路径进行比较,或者甚至只是将内容类型与默认列表[“image/jpeg”,“image/png”等)进行比较)。

总之,这里的其传递回基于两种缩略图式的通用图标的路径方法(在您的情况:拇指和:大)和内容类型:

# Generates a path to the thumbnail image for the given content type 
# and image size. 
# 
# e.g. a :small thumbnail with a content type of text/html, the file name 
#  would have the filename icon.small.text.html.png 
# 
# If no such thumbnail can be found a generic one is returned 
def generic_icon_path(style = image.default_style) 
    url = "/images/attachments/icon.#{style.to_s}.#{attachment_content_type.sub('/', '.')}.png" 
    if File.exists? "#{RAILS_ROOT}/public/#{url}" 
    url 
    else 
    "/images/attachments/icon.#{style.to_s}.default.png" 
    end 
end 

然后,加一个新的缩略图,我只是用正确的文件名约定将PNG文件添加到/images/attachments/。我thumbail风格被称为:小,我已经定义了Word,Excel和纯文本样式,以便在目前的时间,我有:

icon.small.application.msword.png 
icon.small.text.plain.png 
icon.small.application.vnd.ms-excel.png 
icon.small.application.vnd.openxmlformats-officedocument.spreadsheetml.sheet.png 
icon.small.application.vnd.openxmlformats-officedocument.wordprocessingml.document.png 

如果内容类型不支持,有一个通用的“所有”图标显示:

icon.small.default.png 
+0

太棒了!非常感谢。我会在早上第一时间尝试一下。似乎正是我想要做的。 – Chelsea 2009-07-31 03:26:51

0

您可能会从您的资产中继承一些文件类型,例如视频,并指定一个不同:

has_attached_file:媒体,...,:风格=> {....}

看一看这个教程video thumbnails

相关问题