使用不同文件类型上载Carrierwave文件

我有以下作为我的FileUploader:

class FileUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick version :thumb, if: :image? do # For images, do stuff here end version :preview, if: :pdf? do # For pdf, do stuff here end protected def image?(new_file) new_file.content_type.start_with? 'image' end def pdf?(new_file) new_file.content_type.start_with? 'application' end end 

我从carrierwave github页面得到了这个。 它主要起作用,但如果我不想要不同的版本呢? 我基本上只是想做某些过程,如果它是pdf,或某些过程,如果它是一个图像。 我可能会在将来允许其他类型的文件,所以如果我有一个简单的方法也可以这样做很酷。

举个例子,我可能想要使用imgoptim(如果它是图像),然后使用pdf优化库(如果它是pdf等)。

我试过了:

 if file.content_type = "application/pdf" # Do pdf things elsif file.content_type.start_with? 'image' # Do image things end 

但得到错误: NameError: (undefined local variable or method FileUploader:Class`的NameError: (undefined local variable or method文件

你应该尝试这样使用

 class FileUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick process :process_image, if: :image? process :process_pdf, if: :pdf? protected def image?(new_file) new_file.content_type.start_with? 'image' end def pdf?(new_file) new_file.content_type.start_with? 'application' end def process_image # I process image here end def process_pdf # I process pdf here end end 

该exception表示您正在类级别范围内调用实例变量。 添加调试器断点并打印出自己,您将了解正在发生的事情。

解决方法是将逻辑包装到实例方法中,并将此方法用作默认进程。

 process :process_file def process_file if file.content_type = "application/pdf" # Do pdf things elsif file.content_type.start_with? 'image' # Do image things end end 

通过这样做,您可以摆脱不需要的版本,并根据mime类型处理您想要的任何内容。

尝试在process使用,例如

 process :action, :if => :image? 

相关: 使用Carrierwave的条件版本/过程