CarrierWave:为多种类型的文件创建1个上传器

我想为多种类型的文件(图像,PDF,video)创建1个上传器

对于每个content_type将执行不同的操作

我如何定义文件的content_type?

例如:

if image? version :thumb do process :proper_resize end elsif video? version :thumb do something end end 

我遇到了这个,它看起来像是如何解决这个问题的一个例子: https : //gist.github.com/995663 。

当您调用mount_uploader ,首先会加载上传mount_uploader ,此时像if image? 还是elsif video? 将无法正常工作,因为尚未定义上传文件。 您需要在实例化类时调用方法。

我上面给出的链接是什么,重写了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 

然后,您可以使用它来调用过去的过程

 IMAGE_EXTENSIONS = %w(jpg jpeg gif png) DOCUMENT_EXTENSIONS = %(exe pdf doc docm xls) def extension_white_list IMAGE_EXTENSIONS + DOCUMENT_EXTENSIONS end process_extensions IMAGE_EXTENSIONS, :resize_to_fit => [1024, 768] 

对于版本,在wavewave wiki上有一个页面,允许您有条件地处理版本,如果您在> 0.5.4。 https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing 。 您必须将版本代码更改为如下所示:

 version :big, :if => :image? do process :resize_to_limit => [160, 100] end protected def image?(new_file) new_file.content_type.include? 'image' end