2011-09-08 92 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

相关问题