我正在使用带有 Ruby on Rails 的 Paperclip 将 Assets 附加到模型,这些 Assets 可以是任何文件类型,目前仅当 Assets 是图像时才会生成缩略图。我希望能够为其他文件显示不同的默认图像,方法是在上传时生成文件的缩略图,或者使用 default_url 进行设置,但到目前为止我找不到任何资源来帮助解决这个问题,我一个人无处可去。
我的模型如下:
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"
如果生成失败,或者在默认 url 中使用 :content_type 之类的内容,是否有人有任何资源可以生成自定义缩略图?我已经查看了源代码,但无处可寻。
谢谢!
最佳答案
我实际上已经实现了这个非常相同的功能。 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,或基于 Assets 内容类型(下面讨论)的通用 PNG 图标的本地路径。
has_thumbnail?
方法确定此 Assets 是否已为其生成缩略图。这是我在自己的 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
关于ruby-on-rails - 带有 Paperclip 的文件类型的自定义缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1209179/