2011-06-28 40 views
2

我用下面的代碼從上傳的文件創建Asset S:如何僅使用回形針創建圖像文件的縮略圖?

def upload 
    uploader = User.find_by_id(params[:uploader_id]) 
    params[:assets].each do |file| 
    new_asset = uploader.assets.build(:asset => file) # Here the error appears 
    new_asset.save 
    end 
    ... 
end 

我注意到,當我上傳非圖片文件,例如my.xlsx,我得到了以下錯誤:

[paperclip] identify -format %wx%h "C:/temp/stream20110628-460-3vqjnd.xlsx[0]" 2>NUL 
[paperclip] An error was received while processing: 
#<Paperclip::NotIdentifiedByImageMagickError: C:/temp/stream20110628-460-3vqjnd.xlsx is 
not recognized by the 'identify' command.> 

(對於圖像文件,一切工作正常:縮略圖被創建,並且沒有錯誤)

是不是因爲回形針試圖創建my.xlsx縮略圖?

什麼配置會只爲圖像文件創建縮略圖

下面是一些相關的代碼:

class Asset < ActiveRecord::Base 
    belongs_to :uploader, :class_name => "User" 
    has_attached_file :asset, :styles => { :thumb => "80x80#" } 
end 

回答

8

我用下面的很好的解決方案:

before_post_process :image? 

def image? 
    (asset_content_type =~ SUPPORTED_IMAGES_REGEX).present? 
end 

其中:

SUPPORTED_IMAGE_FORMATS = ["image/jpeg", "image/png", "image/gif", "image/bmp"] 
SUPPORTED_IMAGES_REGEX = Regexp.new('\A(' + SUPPORTED_IMAGE_FORMATS.join('|') + ')\Z') 
0

更改has_attached_file行改爲:

has_attached_file :asset, :styles => { :thumb=> "80x80#" }, :whiny_thumbnails => false 

這將阻止它沒有創建縮略圖時引發錯誤。但請注意,如果在處理圖像時發生錯誤,則不會引發錯誤。

+0

我不喜歡掩蓋錯誤。它應該是一個很好的方式來定義哪些文件將創建縮略圖... –