我实际上已经实现了这个完全相同的功能。 Paperclip 为我的所有图像和 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
这将返回存储在 S3 上的缩略图的 URL,或基于资产内容类型的通用 PNG 图标的本地路径(如下所述)。这has_thumbnail?
方法确定该资产是否已为其生成缩略图。这是我在我自己的 Paperclip 分支中添加的内容,但您可以用自己的逻辑替换(我不确定确定这一点的“标准”方法,也许将该路径与您定义的“缺失”路径进行比较,甚至只是将内容类型与默认列表[“image/jpeg”、“image/png”]等进行比较。
无论如何,这是根据缩略图样式(在您的情况下为:thumb 和:large)和内容类型将路径传回通用图标的方法:
# 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/
使用正确的文件名约定。我的缩略图样式称为 :small,我已经为 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