【问题标题】:use base64 image with Carrierwave使用带有 Carrierwave 的 base64 图像
【发布时间】:2011-10-01 19:20:00
【问题描述】:

我想执行与 base64 photo and paperclip -Rails 类似的操作,但使用 Carrierwave。 谁能解释我在 Carrierwave 中使用 base64 图像吗?

【问题讨论】:

    标签: ruby-on-rails-3 base64 carrierwave


    【解决方案1】:
    class ImageUploader < CarrierWave::Uploader::Base
    
      class FilelessIO < StringIO
        attr_accessor :original_filename
        attr_accessor :content_type
      end
    
      before :cache, :convert_base64
    
      def convert_base64(file)
        if file.respond_to?(:original_filename) &&
            file.original_filename.match(/^base64:/)
          fname = file.original_filename.gsub(/^base64:/, '')
          ctype = file.content_type
          decoded = Base64.decode64(file.read)
          file.file.tempfile.close!
          decoded = FilelessIO.new(decoded)
          decoded.original_filename = fname
          decoded.content_type = ctype
          file.__send__ :file=, decoded
        end
        file
      end
    

    【讨论】:

    • 如何通过控制器保存文件?你也有这方面的样品吗?
    【解决方案2】:

    接受的答案对我不起作用(v0.9)。 好像是在缓存回调之前检查失败。

    此实现有效:

    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
    

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多