Che*_*sea 13 file-upload ruby-on-rails image thumbnails paperclip
我正在使用带有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"
Run Code Online (Sandbox Code Playgroud)
如果生成失败,有没有人有任何资源用于生成自定义缩略图,或者在默认URL中返回类似于:content_type的内容?我查看了源代码并且无法到达任何地方.
谢谢!
Oll*_*lly 17
我实际上已经实现了这个相同的功能.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
Run Code Online (Sandbox Code Playgroud)
这将返回存储在S3上的缩略图的URL,或基于资产内容类型的通用PNG图标的本地路径(下面讨论).该has_thumbnail?方法确定该资产是否已为其生成缩略图.这是我在自己的Paperclip分支中添加的东西,但你可以用你自己的逻辑替换(我不确定'标准'方法来确定这个,也许比较路径与你定义的'缺失'路径,甚至只是将内容类型与默认列表["image/jpeg","image/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
Run Code Online (Sandbox Code Playgroud)
然后,要添加新的缩略图,我只需/images/attachments/使用正确的文件名约定添加PNG文件.我的拇指风格被称为:小,我已经定义了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
Run Code Online (Sandbox Code Playgroud)
如果不支持内容类型,则会显示一个通用的"全部捕获"图标:
icon.small.default.png
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7168 次 |
| 最近记录: |