问题描述
我想为多种类型的文件(图像,pdf,视频)创建1个上传器
I want to create 1 uploader for multiple types of files (images, pdf, video)
对于每种content_type都会有不同的操作
For each content_type will different actions
如何定义文件的content_type?
How I can define what content_type of file?
例如:
if image?
version :thumb do
process :proper_resize
end
elsif video?
version :thumb do
something
end
end
推荐答案
我遇到了这个问题,它看起来像是解决此问题的示例:。
I came across this, and it looks like an example of how to solve this problem: https://gist.github.com/995663.
当您调用 mount_uploader
时,首先会加载上载器,此时 if图片?
或 elsif视频?
不起作用,因为还没有定义要上传的文件。您需要在实例化类时调用这些方法。
The uploader first gets loaded when you call mount_uploader
, at which point things like if image?
or elsif video?
won't work, because there is no file to upload defined yet. You'll need the methods to be called when the class is instantiated instead.
我在上面给出的链接的作用是重写 process
方法,以便它获取文件列表扩展名,并且仅当您的文件与这些扩展名之一匹配时才进行处理
What the link I gave above does, is rewrite the process
method, so that it takes a list of file extensions, and processes only if your file matches one of those extensions
# create a new "process_extensions" method. It is like "process", except
# it takes an array of extensions as the first parameter, and registers
# a trampoline method which checks the extension before invocation
def self.process_extensions(*args)
extensions = args.shift
args.each do |arg|
if arg.is_a?(Hash)
arg.each do |method, args|
processors.push([:process_trampoline, [extensions, method, args]])
end
else
processors.push([:process_trampoline, [extensions, arg, []]])
end
end
end
# our trampoline method which only performs processing if the extension matches
def process_trampoline(extensions, method, args)
extension = File.extname(original_filename).downcase
extension = extension[1..-1] if extension[0,1] == '.'
self.send(method, *args) if extensions.include?(extension)
end
然后可以使用这就是所谓的处理过程
You can then use this to call what used to be process
IMAGE_EXTENSIONS = %w(jpg jpeg gif png)
DOCUMENT_EXTENSIONS = %(exe pdf doc docm xls)
def extension_white_list
IMAGE_EXTENSIONS + DOCUMENT_EXTENSIONS
end
process_extensions IMAGE_EXTENSIONS, :resize_to_fit => [1024, 768]
对于版本,carrierwave Wiki上有一个页面,可让您有条件地进行处理版本,如果您的版本> 0.5.4。 。您必须更改版本代码,如下所示:
For versions, there's a page on the carrierwave wiki that allows you to conditionally process versions, if you're on >0.5.4. https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing. You'll have to change the version code to look like this:
version :big, :if => :image? do
process :resize_to_limit => [160, 100]
end
protected
def image?(new_file)
new_file.content_type.include? 'image'
end
这篇关于CarrierWave:为多种文件类型创建1个上传器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!