How to load a Base 64 image in a Rails paperclip

I have tried a million different online tutorials on how to download a Base64 image from an iOS app to my rails app. It seems that no matter how I format the request, it simply will not be accepted.

Does anyone know how to load a Base64 image into a clip?

I tried to send the parameter as JSON

{ "thumbnail_image": "base64_data..." }

I also tried adding the data url

{ "thumbnail_image": "data:image/jpeg;base64,alkwdjlaks..." }

I tried sending a JSON object with and without a url

{ "thumbnail_image": { "filename": "thumbnail.jpg", "file_data": "base64_data...", "content_type": "image/jpeg" } }

I sequentially get these Paperclip::NoHandlerError, and then it uploads a giant frame of data to my log.

+4
source share
2 answers

Base64 . ,

, , , Rails. , , , , , .

Paperclip 4.2.1 Base64 GIF :

:

class Thing
    has_attached_file :image

POST:

{
    "thumbnail_data:" "data:image/gif;base64,iVBORw0KGgo..."
}

, , original_filename. , , :

def create
    image = Paperclip.io_adapters.for(params[:thumbnail_data]) 
    image.original_filename = "something.gif"
    Thing.create!(image: image)
    ...
end

AFAIK Paperclip base64 3.5.0.

, !

+8

, , , ,

class FooBar < ActiveRecord::Base
  has_attached_file :thumbnail_image
  validates_attachment_content_type :thumbnail_image,
                                     content_type: %w(image/jpeg image/jpg image/png image/gif),
                                     message: "is not gif, png, jpg, or jpeg." 

  attr_accessor :base64_thumbnail_image

  # call this explicitly from the controller or in an after_save callback
  # after setting the base64_thumbnail_image attribute
  def save_base64_thumbnail_image
    if base64_thumbnail_image.present?
      file_path = "tmp/foo_bar_thumbnail_image_#{self.id}.png"
      File.open(file_path, 'wb') { |f| f.write(Base64.decode64(base64_thumbnail_image)) }
      # set the paperclip attribute and let it do its thing
      self.thumbnail_image = File.new(file_path, 'r')
    end
  end  
end

# params should be base64_thumbnail_image, not thumbnail_image in this case
+1

All Articles