【问题标题】:Carrierwave file upload with different file types不同文件类型的载波文件上传
【发布时间】:2015-08-22 07:04:34
【问题描述】:

我的 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 methodfile' for FileUploader:Class`

【问题讨论】:

  • 这个响应状态实际上不是内部服务器错误500,这可能意味着它可能在您尝试请求控制器时在某个地方死亡。您也可以发布您的模型和控制器吗?

标签: ruby-on-rails ruby image pdf carrierwave


【解决方案1】:

你应该尝试这样使用

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

【讨论】:

    【解决方案2】:

    尝试在process 中使用if,例如

    process :action, :if => :image?
    

    相关: Conditional versions/process with Carrierwave

    【讨论】:

      【解决方案3】:

      该异常表明您正在类级别范围内调用实例变量。 添加一个调试器断点并打印出self你就会明白发生了什么。

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

      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 类型处理您想要的任何内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-11
        • 2018-09-22
        • 1970-01-01
        • 2014-01-06
        • 2018-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多