如何制作自定义载波后处理器?

jrg*_*jrg 6 ruby-on-rails-3 carrierwave

我需要对不是图像的文件上传进行一些后期处理 - 在回形针中我可以有一个自定义的后处理器,但我找不到任何方法在carrierwave中执行此操作.

Ruby 1.9.3,Rails 3.2.7和CarrierWave 0.6.2.

Til*_*ilo 7

OP的问题是如何处理不是图像的文件.

请在GitHub上查看此源文件: carrierwave/lib/carrierwave/uploader/processing.rb 并查看注释.

您将创建自己的CarrierWave上传器子类并将其安装在您的模型中,如下所示:

  def MyModel < ActiveRecord::Base

    # this is where the uploaded file will be available in your model,
    # as a `MyUploader` instance:
    #
    mount_uploader :uploaded_file, MyUploader

    ... 
  end
Run Code Online (Sandbox Code Playgroud)

请注意,它安装在ActiveRecord属性上:uploaded_file.这意味着当您:uploaded_file从模型访问时,您将获得上载的特定文件的CarrierWave上传程序实例.

您可以在上传器中简单地定义处理,如下所示:

  class MyUploader < CarrierWave:Uploader::Base
    process :my_custom_processing => [param1,param2,param3]

    def my_custom_processing(param1,param2,param3)
      ...
      # e.g. you could call a method which is defined elsewhere,
      # which operates on a file:
      my_nifty_file_processor( self.uploaded_file ) 
      #
      # or you could just do this directly:
      uploaded_data = self.uploaded_file.read
      ...
    end
  end
Run Code Online (Sandbox Code Playgroud)

在里面my_nifty_file_processor,你只需要调用read传入的对象来读取文件.

CarrierWave允许您调用read任何Uploader实例(=上传文件的任何实例),它将读取该文件.

还有一个提示:

有时您需要访问上传文件的上传器中的ActiveRecord模型.

只需在上传代码中访问它,如下所示:

      self.model
Run Code Online (Sandbox Code Playgroud)

这使您可以直接在AR模型中存储有关上载文件的其他信息,例如格式.


Mac*_*iuk 2

我写了一篇关于如何创建自定义后处理器来创建视频缩略图的博客文章,也许您会发现它很有用。

https://prograils.com/posts/video-encoding-processor-for-rierwave/