use base64 image with Carrierwave

后端 未结 2 941
一生所求
一生所求 2020-12-28 12:06

I want to perform the similar thing as from base64 photo and paperclip -Rails, but with Carrierwave. Could anybody explain me using of base64 images in Carrierwave?

2条回答
  •  孤独总比滥情好
    2020-12-28 12:40

    The accepted answer did not worked for me (v0.9). It seems to be a check that fails before the cache callback.

    This implementation works:

    class ImageUploader < CarrierWave::Uploader::Base
    
      # Mimick an UploadedFile.
      class FilelessIO < StringIO
        attr_accessor :original_filename
        attr_accessor :content_type
      end
    
      # Param must be a hash with to 'base64_contents' and 'filename'.
      def cache!(file)
        if file.respond_to?(:has_key?) && file.has_key?(:base64_contents) && file.has_key?(:filename)
          local_file = FilelessIO.new(Base64.decode64(file[:base64_contents]))
          local_file.original_filename = file[:filename]
          extension = File.extname(file[:filename])[1..-1]
          local_file.content_type = Mime::Type.lookup_by_extension(extension).to_s
          super(local_file)
        else
          super(file)
        end
      end
    
    end
    

提交回复
热议问题