我正在使用带有Ruby on Rails的Paperclip将资源附加到模型,这些资产可以是任何文件类型,并且当资产是图像时,仅生成缩略图。我希望能够为其他文件显示不同的默认图像,或者通过在上传时生成文件的缩略图,或者使用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"  

如果生成失败,是否有人有任何资源可用于生成自定义缩略图,或者在默认网址中返回类似于: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,或基于资产内容类型的通用PNG图标的本地路径(如下所述)。 has_thumbnail?方法确定此资产是否已为其生成缩略图。这是我在自己的Paperclip分支中添加的内容,但您可以用自己的逻辑替换(我不确定'标准'方法来确定这一点,可能将路径与您定义的'缺失'路径进行比较,甚至只是将内容类型与默认列表[&quot; image / jpeg&quot;,&quot; image / png&quot;]等进行比较。)

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

# 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 / 中,并使用正确的文件名约定。我的拇指风格被称为:小,我已经定义了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

其他提示

您可以从资产继承某些文件类型,例如视频并指定其他内容:

has_attached_file:media,...,:style =&gt; {....}

请参阅本教程,了解视频缩略图

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top