使用不同文件类型上载Carrierwave文件 [英] Carrierwave file upload with different file types

查看:255
本文介绍了使用不同文件类型上载Carrierwave文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下作为我的FileUploader:

I have the following as my 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,或某些过程,如果它是一个图像。我可能会在将来允许其他类型的文件,所以如果我能够有一个简单的方法来做它也会很酷。

I got this from the carrierwave github page. It mostly works, but what If I don't want different versions? I basically just want to do certain processes if it's a pdf, or certain processes if it's an image. I may allow other types of files in the future as well, so it'd be cool if I could have an easy way to do that as well.

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

For an example, I may want to use an imgoptim if it's an image, and then a pdf optimizing library if it's a pdf, etc.

我试过:

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

但是得到错误: NameError :(未定义的局部变量或方法文件'for FileUploader:Class`

but get the error: NameError: (undefined local variable or methodfile' for FileUploader:Class`

推荐答案

你应该尝试这样使用

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

这篇关于使用不同文件类型上载Carrierwave文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆