Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload HTML5 canvas as a blob

I have a canvas, which I can paint to the DOM without a problem as well as save for the user locally using:

storCanvas.toBlob(function(blob) { saveAs(blob, name + ".png");});

(note: I've included canvas-toBlob.js for cross platform support, from http://eligrey.com/blog/post/saving-generated-files-on-the-client-side)

Now, what I would like to do is send the same canvas element to the server. I thought I could do something like:

storCanvas.toBlob(function(blob) {upload(blob);});

where upload(blob); is:

function upload(blobOrFile)
{
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload_file.php', true);
    xhr.onload = function(e) { /*uploaded*/ };

    // Listen to the upload progress.
    var progressBar = document.querySelector('progress');
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable)
        {
          progressBar.value = (e.loaded / e.total) * 100;
          progressBar.textContent = progressBar.value;
        }
    };
    xhr.send(blobOrFile);

}

(cribbed from: http://www.html5rocks.com/en/tutorials/file/xhr2/)

Now, I thought I this would work, but my PHP page (which I can do a POST to successfully using a standard HTML form) reports back (via firebug) that it got an invalid file of 0kB. I assume that the issue is in my conversion to a blob, but I'm not sure the correct way to go about it...

like image 850
TheJBW Avatar asked Apr 25 '12 10:04

TheJBW


People also ask

How do you convert a canvas to a blob?

The HTMLCanvasElement. toBlob() method creates a Blob object representing the image contained in the canvas. This file may be cached on the disk or stored in memory at the discretion of the user agent. The desired file format and image quality may be specified.

Can I use canvas to blob?

If you're wondering whether you can draw image blobs to another canvas context, the answer is -- in Firefox and Chrome -- yes, absolutely! You can do this with the createImageBitmap() API, which is also landing in Chrome 50.


1 Answers

I came across the same problem when learning about blobs myself. I believe the problem is in submitting the blob itself through the XMLHttpRequest rather than putting it inside a FormData like this:

canvas.toBlob(function(blob) {
  var formData = new FormData(); //this will submit as a "multipart/form-data" request
  formData.append("image_name", blob); //"image_name" is what the server will call the blob
  upload(formData); //upload the "formData", not the "blob"
});

Hope this helps.

like image 88
Patrick Roberts Avatar answered Sep 20 '22 18:09

Patrick Roberts