简体   繁体   中英

How to save a Canvas via Paperclip

I have been working with two approaches, but the goal is just to save the canvas via Paperclip.

First approach

Canvas to Base64 and then add base64 to params with ajax

    $(document).on('click', '#save_canvas', function() {
      var base64Data = canvas.toDataURL()

      $.ajax({
        type:    "POST",
        url:     "pictures/",
        data:    { base64: base64Data },
        success: function(post){ console.log('success') },
        error:   function(post){ console.log(this) }
      })
    })



Access params[:base64] via Paperclip.adapters_io

  def create
    @picture = Picture.new(picture_params)
    # ...

    image = Paperclip.io_adapters.for(params[:base64])
    image.original_filename = "canvas.png"

    @picture.image = image

    @picture.save
    redirect_to @picture
  end


I think this is not working, to start, because this is only including base64 in params and missing all the other required params.


Second approach

Canvas to Base64 and then manually (just to make it work and keep working from there) copy data from the console and paste it into a form field.

= link_to " Base64", "#", remote: true, onclick: "console.log(canvas.toDataURL('png'))" 
= form_for @picture, html: { multipart: true } do |form|
  = form.text_field :base64
  = form.submit



Access params[:picture][:base64] via Paperclip.adapters_io

  def create
    @picture = Picture.new(picture_params)

    image = Paperclip.io_adapters.for(params[:picture][:base64])
    image.original_filename = "canvas.png"

    @picture.image = image

    @picture.save
    redirect_to @picture
  end

With this approach, I can save the canvas. But I found two issues:

1) I have to eliminate the copy/paste step.
2) Canvas can generate very long strings with more than 1 million characters (that's crazy) and form field is not allowing such a huge length.



This is a Rails 4.2 project using Paperclip 4.3 and will be hosted on Heroku.
Thanks!

The first approach should be the good one. The string created put the mime type at start, and paperclip can handle base64 string.

Example in one of our projects (working well)

 #in our coffeescript (own ajax method, no jquery, but same behavior)
 ajax("images",
  method: "post",
  data: {image: @state.src}
 ).then((result) =>
   console.log "yey"
 )

 #In the image_controller, to add an uploaded picture
 def create
   current_user.photos.new picture: params[:image]
 end

Our paperclip version is 4.3.3. We use it with Html5 File API, not canvas, but the output (base64) is exactly same format than the Canvas#toDataUrl , as long as we can display a preview in a src attribute of an image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM