如何制作定制的载波后处理器? [英] How can I make a custom carrierwave post processor?

查看:76
本文介绍了如何制作定制的载波后处理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to do some post processing on a file upload that isn't images - in paperclip I can have a custom post processor, but I can't find any way to do this in carrierwave.

Ruby 1.9.3,Rails 3.2.7和CarrierWave 0.6.2.

Ruby 1.9.3, Rails 3.2.7 and CarrierWave 0.6.2.

推荐答案

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

The OP's question was how to process files which are not images.

请在GitHub上查看此源文件: carrierwave/lib/carrierwave/uploader/processing.rb 并检查评论.

Please have a look at this source file on GitHub: carrierwave/lib/carrierwave/uploader/processing.rb and check the comments.

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

You'll have create your own CarrierWave uploader sub-class and mount it in your model like this:

  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

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

Please note that it's mounted on the ActiveRecord attribute :uploaded_file. This means when you access :uploaded_file from your model, you will get an instance of your CarrierWave uploader for the particular file which was uploaded.

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

You can simply define your processing inside your uploader as follows:

  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

my_nifty_file_processor 内,您只需对传入的对象调用 read 即可读取文件.

Inside my_nifty_file_processor, you would simply call read on the object that gets passed in to read the file.

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

CarrierWave lets you call read on any Uploader instance (= any instance of an uploaded file) and it will read that file.

另一个提示:

有时您需要在上传器中访问ActiveRecord模型,并为其上传文件.

Sometimes you need to access the ActiveRecord model within your uploader, for which the file was uploaded.

像这样简单地在您的上传器代码中访问它:

Simply access it inside your uploader code like this:

      self.model

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

This lets you store additional information about the uploaded file, such as format, directly in your AR model.

这篇关于如何制作定制的载波后处理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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