How to save a Canvas via Paperclip

半腔热情 提交于 2019-12-08 02:43:40

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/36376215/how-to-save-a-canvas-via-paperclip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!