使用Paperclip自定义缩略图文件类型

我正在使用带有Ruby on Rails的Paperclip将资源附加到模型,这些资产可以是任何文件类型,并且如果资产是图像,则仅生成缩略图。 我希望能够为其他文件显示不同的默认图像,或者通过在上传时生成文件的缩略图,或者使用default_url设置一些内容,但到目前为止我找不到任何资源来帮助解决这个问题。我自己也没有。

我的模型如下:

class Asset  :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的内容? 我查看了源代码并且无法到达任何地方。

谢谢!

我实际上实现了这个相同的function。 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? method确定此资产是否已为其生成缩略图。 这是我在自己的Paperclip分支中添加的东西,但你可以用你自己的逻辑代替(我不确定’标准’方法来确定这个,也许比较路径和你定义的’缺失’路径,甚至只是将内容类型与默认列表[“image / jpeg”,“image / png”]等进行比较。

无论如何,这里的方法是根据缩略图样式(在您的情况下:拇指和:大)和内容类型将路径传递回通用图标:

 # Generates a path to the thumbnail image for the given content type # and image size. # # eg 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/ 。 我的拇指风格被称为:小,我已经定义了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 

您可以从您的资产inheritance一些文件类型,例如video并指定不同的:

has_attached_file:media,…,:style => {….}

看一下本教程的video缩略图 。