blog.robotex.de

Handle base64 encoded attachments with paperclip < 3.5.0

module Base64EncodedAssets
  extend ActiveSupport::Concern

  included do
    before_validation :decode_base64_asset
  end

  def decode_base64_asset
    if asset.uploaded_file =~ /^data:([-\w]+\/[-\w\+]+);base64,(.*)/
      content_type = $LAST_MATCH_INFO[1]
      asset_data   = $LAST_MATCH_INFO[2]
      decoded_data = Base64.decode64(asset_data)

      file_extension = Rack::Mime::MIME_TYPES.invert[content_type]

      data = StringIO.new(decoded_data)

      data.class_eval do
        attr_accessor :content_type, :original_filename
      end

      data.content_type = content_type
      data.original_filename = File.basename("#{SecureRandom.uuid}#{file_extension}")

      self.asset = data
    end
  end
end

include Base64EncodedAssets if Paperclip::VERSION < '3.5.0'

Back