CarrierWave和文件扩展名取决于其内容

CarrierWave和文件扩展名取决于其内容

本文介绍了CarrierWave和文件扩展名取决于其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使CarrierWave根据文件名
向文件名添加正确的扩展名?例如,如果我上载文件徽标(PNG文件
,不带扩展名),CarrierWave应该将其另存为 logo.png。并将文件 img.gif(扩展名不正确的JPG文件)分别保存为 img.jpg。

How can I make CarrierWave add correct extension to filename dependingon its contents? For example, if I upload file "logo" (PNG filewithout extension) CarrierWave should save it as "logo.png". And file "img.gif" (JPG file with incorrect extension) respectively should be saved as "img.jpg".

推荐答案

您可以执行几项操作,具体取决于您是使用进程还是版本来执行此操作。

There's a couple of things you can do, depending on if you're using process or version to do this.

如果是版本,carrierwave Wiki可以提供条件版本。

If it's a version, the carrierwave wiki has a way to do conditional versions. https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing

version :big, :if => :png? do
  process ...
end

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

如果您使用的是流程方法,您可能需要看一下:。

If you're using the process method, you might want to take a look at this: https://gist.github.com/995663.

将这些内容添加到您的代码中以解决进程具有的约束

Add these into your code to get around the constraints that process has

# 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, selectively on each file type

PNG = %w(png)
JPG = %w(jpg jpeg)
GIF = %w(gif)
def extension_white_list
  PNG + JPG + GIF
end

process_extensions PNG, :resize_to_fit => [1024, 768]
process_extensions JPG, :...
process_extensions GIF, :...

这篇关于CarrierWave和文件扩展名取决于其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 09:13