Carrierwave encode file to base64 as process

2019-09-17 14:22发布

问题:

I am trying to solve this. I would like to encode file as base64 as one of the process.

My code so far looks like

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  include CarrierWave::MimeTypes

  storage :file

  def extension_white_list
    %w(jpg jpeg png)
  end

  def store_dir
    "/tmp/images/#{model.class.to_s.underscore}/#{model.id}"
  end

  process :set_content_type
  process :format_to_jpg
  process :strip_metadata
  process :encode_base64

  def format_to_jpg
    manipulate! do |img|
      img.format 'jpg'
      img
    end
  end

  def strip_metadata
    manipulate! do |img|
      img.strip
      img
    end
  end

  def encode_base64
    #What should be here?
  end
end

I am not sure what I should place in the encode_base64 method. The method for encoding is Base64.encode64() as parameter should be sent the file content (self.read probably). but I am not sure how I should do this to follow Carrierwave best practices.

回答1:

Find out that I don't have to do anything special here.

def encode_base64
  File.write(path,Base64.encode64(File.read(path)))
end

does the magic