I've been trying to re-implement an HTML5 image uploader like the one on the Mozilla Hacks site, but that works with WebKit browsers. Part of the task is to extract an image file from the canvas
object and append it to a FormData object for upload.
The issue is that while canvas
has the toDataURL
function to return a representation of the image file, the FormData object only accepts File or Blob objects from the File API.
The Mozilla solution used the following Firefox-only function on canvas
:
var file = canvas.mozGetAsFile("foo.png");
...which isn't available on WebKit browsers. The best solution I could think of is to find some way to convert a Data URI into a File object, which I thought might be part of the File API, but I can't for the life of me find something to do that.
Is it possible? If not, any alternatives?
Thanks.
Firefox has canvas.toBlob() and canvas.mozGetAsFile() methods.
But other browsers do not.
We can get dataurl from canvas and then convert dataurl to blob object.
Here is my
dataURLtoBlob()
function. It's very short.Use this function with FormData to handle your canvas or dataurl.
For example:
Also, you can create a
HTMLCanvasElement.prototype.toBlob
method for non gecko engine browser.Now
canvas.toBlob()
works for all modern browsers not only Firefox. For example:toDataURL gives you a string and you can put that string to a hidden input.
After playing around with a few things, I managed to figure this out myself.
First of all, this will convert a dataURI to a Blob:
From there, appending the data to a form such that it will be uploaded as a file is easy:
Here is an ES6 version of Stoive's answer:
Usage:
make it simple :D
I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this: