-1

I know this question is asked before but my case is different. I don't want to browse the client's computer, I want to add the "post it" button to the image he was drawing. it's a drawing web app. I don't think this needs any code from me. Thanks a lot. EDIT: Rails html

<%= form_for @post, html: { multipart: true } do |f| %>
<br>
 <%= f.label :image %>
 <%= f.file_field :image, id: "pictureInput", class: "pictureInput" %> <<---
 <%= f.text_area :title %>
 <%= f.label :title %>
 <br>
 <%= f.submit %>
<% end %> 
<div id="post-image-preview">
</div>

The js is drawing on a canvas.

Malek Zalfana
  • 318
  • 2
  • 11

1 Answers1

0

It is not possible to set the FileList property of an <input type="file"> element, as FileList is read-only. You can use FormData(), canvas.toBlob(), XMLHttpRequest() to POST FormData() object containing File object to server

// if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
  value: function(callback, type, quality) {

    var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
      len = binStr.length,
      arr = new Uint8Array(len);

    for (var i = 0; i < len; i++) {
      arr[i] = binStr.charCodeAt(i);
    }

    callback(new Blob([arr], {
      type: type || 'image/png'
    }));
  }
});

canvas.toBlob(function(blob) {
  var data = new FormData();
  data.append("file", blob, "imageName")
  var request = new XMLHttpRequest();
  request.open("POST", "/path/to/server/");
  request.onerror = function(e) {
    console.log(e)
  }
  request.upload.onprogress = function(e) {
    if (e.lengthComputable) {
      console.log(e.loaded, e.total);
    }
  }
  request.send(data);
});
guest271314
  • 1
  • 15
  • 104
  • 177