自定义缩略图文件类型回形针(Custom thumbnails for file types wit

2019-07-31 03:48发布

我用回形针与on Rails的Ruby的资产连接到一个模型中,这些资产可以是任何类型的文件,目前如果资产是图像只生成缩略图。 我希望能够为其他文件,或者是通过生成对上传文件的缩略图,或者设置的东西了与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? 我已经通过源看去,一直没能取得任何进展。

谢谢!

Answer 1:

其实我已经实现了这个同样的功能。 回形针生成所有我的图片和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? 方法确定该资产是否已必须为它生成缩略图。 这是我在我自己的纸夹的叉补充说,但你可以在自己的逻辑代替(我不知道的“标准”的方式来确定这一点,也许路径与你定义的“失踪”的路径相比,甚至只是比较所述内容类型的默认列表[“图像/ JPEG”,“图像/ 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


Answer 2:

你可以有一些类型的文件从你的资产,如视频继承和指定不同的:

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

看看这个教程视频缩略图 。



文章来源: Custom thumbnails for file types with Paperclip