javascript - Convert Data URI to File then append to FormData

ID : 10370

viewed : 18

Tags : javascripthtmlwebkitjavascript

Top 5 Answer for javascript - Convert Data URI to File then append to FormData

vote vote

93

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:

function dataURItoBlob(dataURI) {     // convert base64/URLEncoded data component to raw binary data held in a string     var byteString;     if (dataURI.split(',')[0].indexOf('base64') >= 0)         byteString = atob(dataURI.split(',')[1]);     else         byteString = unescape(dataURI.split(',')[1]);      // separate out the mime component     var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];      // write the bytes of the string to a typed array     var ia = new Uint8Array(byteString.length);     for (var i = 0; i < byteString.length; i++) {         ia[i] = byteString.charCodeAt(i);     }      return new Blob([ia], {type:mimeString}); } 

From there, appending the data to a form such that it will be uploaded as a file is easy:

var dataURL = canvas.toDataURL('image/jpeg', 0.5); var blob = dataURItoBlob(dataURL); var fd = new FormData(document.forms[0]); fd.append("canvasImage", blob); 
vote vote

87

BlobBuilder and ArrayBuffer are now deprecated, here is the top comment's code updated with Blob constructor:

function dataURItoBlob(dataURI) {     var binary = atob(dataURI.split(',')[1]);     var array = [];     for(var i = 0; i < binary.length; i++) {         array.push(binary.charCodeAt(i));     }     return new Blob([new Uint8Array(array)], {type: 'image/jpeg'}); } 
vote vote

77

This one works in iOS and Safari.

You need to use Stoive's ArrayBuffer solution but you can't use BlobBuilder, as vava720 indicates, so here's the mashup of both.

function dataURItoBlob(dataURI) {     var byteString = atob(dataURI.split(',')[1]);     var ab = new ArrayBuffer(byteString.length);     var ia = new Uint8Array(ab);     for (var i = 0; i < byteString.length; i++) {         ia[i] = byteString.charCodeAt(i);     }     return new Blob([ab], { type: 'image/jpeg' }); } 
vote vote

70

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.

function dataURLtoBlob(dataurl) {     var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],         bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);     while(n--){         u8arr[n] = bstr.charCodeAt(n);     }     return new Blob([u8arr], {type:mime}); } 

Use this function with FormData to handle your canvas or dataurl.

For example:

var dataurl = canvas.toDataURL('image/jpeg',0.8); var blob = dataURLtoBlob(dataurl); var fd = new FormData(); fd.append("myFile", blob, "thumb.jpg"); 

Also, you can create a HTMLCanvasElement.prototype.toBlob method for non gecko engine browser.

if(!HTMLCanvasElement.prototype.toBlob){     HTMLCanvasElement.prototype.toBlob = function(callback, type, encoderOptions){         var dataurl = this.toDataURL(type, encoderOptions);         var bstr = atob(dataurl.split(',')[1]), n = bstr.length, u8arr = new Uint8Array(n);         while(n--){             u8arr[n] = bstr.charCodeAt(n);         }         var blob = new Blob([u8arr], {type: type});         callback.call(this, blob);     }; } 

Now canvas.toBlob() works for all modern browsers not only Firefox. For example:

canvas.toBlob(     function(blob){         var fd = new FormData();         fd.append("myFile", blob, "thumb.jpg");         //continue do something...     },     'image/jpeg',     0.8 ); 
vote vote

52

My preferred way is canvas.toBlob()

But anyhow here is yet another way to convert base64 to a blob using fetch ^^,

var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="    fetch(url)  .then(res => res.blob())  .then(blob => {    var fd = new FormData()    fd.append('image', blob, 'filename')        console.log(blob)      // Upload    // fetch('upload', {method: 'POST', body: fd})  })

Top 3 video Explaining javascript - Convert Data URI to File then append to FormData

Related QUESTION?