gpt4 book ai didi

ruby-on-rails - CarrierWave:为多种类型的文件创建 1 个 uploader

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:56 24 4
gpt4 key购买 nike

我想为多种类型的文件(图片、pdf、视频)创建 1 个 uploader

对于每个 content_type 会有不同的 Action

如何定义文件的内容类型?

例如:

if image?
version :thumb do
process :proper_resize
end
elsif video?
version :thumb do
something
end
end

最佳答案

我遇到过这个,它看起来像一个如何解决这个问题的例子:https://gist.github.com/995663 .

uploader 首先在您调用 mount_uploader 时加载,此时 if image?elsif video? 将不起作用,因为还没有定义要上传的文件。您需要在实例化类时调用这些方法。

我在上面给出的链接所做的是重写 process 方法,以便它获取文件扩展名列表,并且仅当您的文件与其中一个扩展名匹配时才处理

# 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

然后你可以用它来调用以前的进程

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。 https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing .您必须将版本代码更改为如下所示:

version :big, :if => :image? do
process :resize_to_limit => [160, 100]
end

protected
def image?(new_file)
new_file.content_type.include? 'image'
end

关于ruby-on-rails - CarrierWave:为多种类型的文件创建 1 个 uploader ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com