Rails 4 CarrierWave(母版)和MiniMagick:更改文件格式

Dan*_*n L 6 carrierwave minimagick imagemagick-convert ruby-on-rails-4

我正在使用Rails 4.2,CarrierWave主分支和MiniMagick 4.3.6(还使用了CarrierWave :: MiniMagick模块)。

根据CarrierWave文档,可以在上载/处理阶段更改文件格式。

但是,我认为该代码无法像所记录的那样工作。我将Amazon S3与fog-awsgem 一起用作我的商店,并且上传到S3的文件仍保留其原始格式。

我的最终目标是上传PDF文档,并在将其保存在S3中时将其处理为png文件。

当我上传图像文件时,一切都按预期工作,它们作为图像正确进入S3。但是,PDF文件仍以“应用程序/ pdf”的内容类型存储在S3中,并且浏览器尝试将其呈现为PDF而不是图像(如果有用,我的上载将在图像滑块中使用)。

有人知道为什么转换过程无法正常进行吗?

模型(models / testimonial.rb):

class Testimonial < ActiveRecord::Base
  mount_uploader :image, TestimonialUploader
end
Run Code Online (Sandbox Code Playgroud)

上传器(uploaders / testimonial_uploader.rb):

class TestimonialUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :fog

  process :convert_file_to_png => [850, 1100]

  def convert_file_to_png(width, height)
    manipulate! do |img|
      img.format("png") do |c|
        c.trim
        c.resize "#{width}x#{height}>"
        c.resize "#{width}x#{height}<"
      end

      img
    end
  end

  def extension_white_list
    %w(jpg jpeg png pdf bmp tif tiff)
  end

  def store_dir
    "testimonials/#{model.uuid}"
  end

  def filename
    super.chomp(File.extname(super)) + ".png" if original_filename.present?
  end
end
Run Code Online (Sandbox Code Playgroud)

更新2016-10-07:工作代码

我被要求用我的解决方案更新此帖子。以下是我几个月来一直在生产中使用的工作代码,没有任何已知问题。

class TestimonialUploader < CarrierWave::Uploader::Base
  # 2015-12-23: note that ImageMagick does not actually seem to work
  include CarrierWave::RMagick

  # Scopes
  #----------------------------------------------------------------------

  # NOOP

  # Macros
  #----------------------------------------------------------------------

  storage :fog

  process convert_file_to_png: [850, 1100]
  process :set_content_type_to_png

  # Associations
  #----------------------------------------------------------------------

  # NOOP

  # Validations
  #----------------------------------------------------------------------

  # NOOP

  # Methods
  #----------------------------------------------------------------------

  def convert_file_to_png(width, height)
    manipulate!(format: "png", read: { density: 400 }) do |img, index, options|
      options = { quality: 100 }
      img.resize_to_fit!(width, height)
    end
  end

  # Required to actually force Amazon S3 to treat it like an image
  def set_content_type_to_png
    self.file.instance_variable_set(:@content_type, "image/png")
  end

  def extension_white_list
    %w(jpg jpeg png pdf bmp tif tiff)
  end

  def store_dir
    "testimonials/#{model.uuid}"
  end

  def filename
    super.chomp(File.extname(super)) + ".png" if original_filename.present?
  end
end
Run Code Online (Sandbox Code Playgroud)