Upload HTML5 canvas as a blob

html, javascript

Solution

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.

Problem

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...

Original source