OP的问题是如何处理非图像文件。
请查看 GitHub 上的源文件:载波/lib/载波/uploader/processing.rb https://github.com/carrierwaveuploader/carrierwave/blob/c2ee2e89d3aa447c6b81186be6d627202d33a97f/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
请注意,它安装在 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
Inside my_nifty_file_processor
,你只需调用read
在传入以读取文件的对象上。
CarrierWave 让您可以打电话read
在任何上传器实例(=上传文件的任何实例)上,它将读取该文件。
还有一提示:
有时,您需要访问上传器中的 ActiveRecord 模型(为其上传文件)。
只需在您的上传器代码中访问它,如下所示:
self.model
这使您可以将有关上传文件的附加信息(例如格式)直接存储在 AR 模型中。