2011-09-08 95 views

回答

3

有幾件事你可以做,取決於你是否使用processversion來做到這一點。

如果是一個版本,carrierwave wiki有辦法做條件版本。 https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing

version :big, :if => :png? do 
    process ... 
end 

protected 
def png?(new_file) 
    new_file.content_type.include? 'png' 
end 

如果您使用的process方法,你可能想看看這個:https://gist.github.com/995663

添加這些到您的代碼,以繞過約束process具有

# create a new "process_extensions" method. It is like "process", except 
# it takes an array of extensions as the first parameter, and registers 
# a trampoline method which checks the extension before invocation 
def self.process_extensions(*args) 
    extensions = args.shift 
    args.each do |arg| 
    if arg.is_a?(Hash) 
     arg.each do |method, args| 
     processors.push([:process_trampoline, [extensions, method, args]]) 
     end 
    else 
     processors.push([:process_trampoline, [extensions, arg, []]]) 
    end 
    end 
end 

# our trampoline method which only performs processing if the extension matches 
def process_trampoline(extensions, method, args) 
    extension = File.extname(original_filename).downcase 
    extension = extension[1..-1] if extension[0,1] == '.' 
    self.send(method, *args) if extensions.include?(extension) 
end 

然後,您可以用它來打電話曾經被認爲是過程,有選擇地對每個文件類型

PNG = %w(png) 
JPG = %w(jpg jpeg) 
GIF = %w(gif) 
def extension_white_list 
    PNG + JPG + GIF 
end 

process_extensions PNG, :resize_to_fit => [1024, 768] 
process_extensions JPG, :... 
process_extensions GIF, :... 
+0

考慮版本路線,如果我想糾正N個版本的M擴展,該怎麼辦?我需要有M * N條件來處理這個問題嗎? – lulalala

2

的問題在於首先確定正確的內容。 Carrierwave使用MimeType gem,它從擴展名中確定其MIME類型。因爲,在你的情況下,擴展是不正確的,你需要一個獲得正確的MIME類型的替代方法。這是我能夠想出的最佳解決方案,但它取決於使用RMagick gem讀取圖像文件的能力。

我遇到了這個問題,不得不爲我的上傳器覆蓋默認的set_content_type方法。這假設你在你的Gemfile中有Rmagick寶石,這樣你就可以從閱讀圖像中獲得正確的mime類型,而不是做出最好的猜測。

注意:如果圖像被僅支持JPG和PNG圖像的Prawn使用,此功能特別有用。

上傳類:

process :set_content_type 

def set_content_type #Note we are overriding the default set_content_type_method for this uploader 
    real_content_type = Magick::Image::read(file.path).first.mime_type 
    if file.respond_to?(:content_type=) 
    file.content_type = real_content_type 
    else 
    file.instance_variable_set(:@content_type, real_content_type) 
    end 
end 

圖片型號:

class Image < ActiveRecord::Base 
    mount_uploader :image, ImageUploader 

    validates_presence_of :image 
    validate :validate_content_type_correctly 

    before_validation :update_image_attributes 

private 
    def update_image_attributes 
    if image.present? && image_changed? 
     self.content_type = image.file.content_type 
    end 
    end 

    def validate_content_type_correctly 
    if not ['image/png', 'image/jpg'].include?(content_type) 
     errors.add_to_base "Image format is not a valid JPEG or PNG." 
     return false 
    else 
     return true 
    end 
    end 
end 

在你的情況,你可以添加,改變在此基礎上正確的MIME類型的擴展名的附加的方法(CONTENT_TYPE )。

+0

讓我走上正軌。 – phillyslick

相關問題