Convert Data URI to File then append to FormData












253














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.










share|improve this question






















  • If you want to save the DataURI of an image in server: stackoverflow.com/a/50131281/5466401
    – Sibin John Mattappallil
    May 2 '18 at 9:49
















253














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.










share|improve this question






















  • If you want to save the DataURI of an image in server: stackoverflow.com/a/50131281/5466401
    – Sibin John Mattappallil
    May 2 '18 at 9:49














253












253








253


185





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.










share|improve this question













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.







javascript html5 webkit






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Feb 15 '11 at 0:40









Stoive

8,11642031




8,11642031












  • If you want to save the DataURI of an image in server: stackoverflow.com/a/50131281/5466401
    – Sibin John Mattappallil
    May 2 '18 at 9:49


















  • If you want to save the DataURI of an image in server: stackoverflow.com/a/50131281/5466401
    – Sibin John Mattappallil
    May 2 '18 at 9:49
















If you want to save the DataURI of an image in server: stackoverflow.com/a/50131281/5466401
– Sibin John Mattappallil
May 2 '18 at 9:49




If you want to save the DataURI of an image in server: stackoverflow.com/a/50131281/5466401
– Sibin John Mattappallil
May 2 '18 at 9:49












14 Answers
14






active

oldest

votes


















423














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);





share|improve this answer



















  • 23




    Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
    – syaz
    Feb 22 '12 at 5:36






  • 1




    @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
    – Stoive
    Feb 18 '13 at 0:58








  • 2




    @stoive In that case why it's not bb.append(ia)?
    – Mimo
    Feb 18 '13 at 4:13








  • 6




    Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
    – TWright
    Aug 2 '14 at 3:25






  • 1




    @TWright, that's based on this answer.
    – Kenny Evitt
    Oct 13 '14 at 19:52



















138














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'});
}





share|improve this answer

















  • 2




    Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
    – DDS
    Mar 14 '13 at 20:28






  • 5




    This doesn't work in Safari.
    – William T.
    Apr 1 '13 at 23:55






  • 2




    Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
    – ObscureRobot
    Apr 10 '13 at 22:29












  • "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
    – Niels Abildgaard
    Jun 16 '14 at 8:42






  • 1




    "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
    – Jasper
    Aug 18 '14 at 10:17





















50














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' });
}





share|improve this answer

















  • 10




    Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    – Per Quested Aronsson
    Sep 23 '13 at 11:09










  • What is with the fallback for iOS6 with webkit prefix? How do you handle this?
    – confile
    Mar 20 '14 at 22:52



















23














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
);





share|improve this answer



















  • 1




    The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
    – Jakob Kruse
    Jun 10 '15 at 12:37






  • 1




    I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
    – Eric Simonton
    Oct 13 '17 at 13:11










  • i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
    – Martian2049
    Mar 4 '18 at 23:17










  • works in IE 11 also for application/pdf !
    – Michal.S
    Nov 6 '18 at 11:07



















19














Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer



function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring

if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}

mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}

return new Blob([new Uint8Array(content)], {type: mimestring});
}





share|improve this answer





























    19














    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})
    })








    share|improve this answer























    • what is fetch and how is it relevant?
      – Ricardo Freitas
      Nov 28 '16 at 17:33










    • Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
      – Endless
      Nov 28 '16 at 17:49






    • 1




      @Endless 'fetch()' a local base64 string... a really clever hack!
      – Diego ZoracKy
      Mar 6 '17 at 21:18



















    12














    The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.



    I don't see any browser yet supporting it :(



    Thanks for this great thread!



    Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):



        var bb;
    try {
    bb = new BlobBuilder();
    } catch(e) {
    try {
    bb = new WebKitBlobBuilder();
    } catch(e) {
    bb = new MozBlobBuilder();
    }
    }


    Were you using another library's polyfill for BlobBuilder?






    share|improve this answer























    • I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
      – Stoive
      Jun 28 '11 at 0:45






    • 1




      BlobBuilder seem to be deprecated in favor of Blob
      – sandstrom
      Oct 10 '12 at 12:57










    • BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
      – Chris Hanson
      Sep 12 '13 at 18:05










    • How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
      – TaylorMac
      Feb 14 '14 at 19:33





















    5














    var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);


    can be used without the try catch.



    Thankx to check_ca. Great work.






    share|improve this answer



















    • 1




      This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
      – TaylorMac
      Feb 14 '14 at 19:30



















    4














    The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:



    function dataURItoBlob (dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs
    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 an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab],{type: mimeString});
    }





    share|improve this answer





























      3














      Here is an ES6 version of Stoive's answer:



      export class ImageDataConverter {
      constructor(dataURI) {
      this.dataURI = dataURI;
      }

      getByteString() {
      let byteString;
      if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
      byteString = atob(this.dataURI.split(',')[1]);
      } else {
      byteString = decodeURI(this.dataURI.split(',')[1]);
      }
      return byteString;
      }

      getMimeString() {
      return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
      }

      convertToTypedArray() {
      let byteString = this.getByteString();
      let ia = new Uint8Array(byteString.length);
      for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
      }
      return ia;
      }

      dataURItoBlob() {
      let mimeString = this.getMimeString();
      let intArray = this.convertToTypedArray();
      return new Blob([intArray], {type: mimeString});
      }
      }


      Usage:



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





      share|improve this answer































        1














        make it simple :D



        function dataURItoBlob(dataURI,mime) {
        // convert base64 to raw binary data held in a string
        // doesn't handle URLEncoded DataURIs

        var byteString = window.atob(dataURI);

        // separate out the mime component


        // write the bytes of the string to an ArrayBuffer
        //var ab = new ArrayBuffer(byteString.length);
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
        }

        // write the ArrayBuffer to a blob, and you're done
        var blob = new Blob([ia], { type: mime });

        return blob;
        }





        share|improve this answer





























          0














          Thanks! @steovi for this solution.



          I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).



          converterDataURItoBlob(dataURI) {
          let byteString;
          let mimeString;
          let ia;

          if (dataURI.split(',')[0].indexOf('base64') >= 0) {
          byteString = atob(dataURI.split(',')[1]);
          } else {
          byteString = encodeURI(dataURI.split(',')[1]);
          }
          // separate out the mime component
          mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

          // write the bytes of the string to a typed array
          ia = new Uint8Array(byteString.length);
          for (var i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
          }
          return new Blob([ia], {type:mimeString});
          }





          share|improve this answer































            -1














            toDataURL gives you a string and you can put that string to a hidden input.






            share|improve this answer





















            • Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
              – Stoive
              Feb 24 '11 at 3:11










            • This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
              – Lucky
              Mar 30 '15 at 8:31



















            -4














            I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:



            var dataURL = canvas.toDataURL("image/jpeg");

            var name = "image.jpg";
            var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});





            share|improve this answer



















            • 2




              Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
              – Pierre Maoui
              Jul 7 '16 at 14:44






            • 2




              WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
              – Ravinder Payal
              Jul 19 '16 at 18:52










            • That is coolest answer I have ever seen, LOL
              – Humoyun
              Oct 4 '18 at 5:09











            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4998908%2fconvert-data-uri-to-file-then-append-to-formdata%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            14 Answers
            14






            active

            oldest

            votes








            14 Answers
            14






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            423














            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);





            share|improve this answer



















            • 23




              Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
              – syaz
              Feb 22 '12 at 5:36






            • 1




              @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
              – Stoive
              Feb 18 '13 at 0:58








            • 2




              @stoive In that case why it's not bb.append(ia)?
              – Mimo
              Feb 18 '13 at 4:13








            • 6




              Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
              – TWright
              Aug 2 '14 at 3:25






            • 1




              @TWright, that's based on this answer.
              – Kenny Evitt
              Oct 13 '14 at 19:52
















            423














            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);





            share|improve this answer



















            • 23




              Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
              – syaz
              Feb 22 '12 at 5:36






            • 1




              @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
              – Stoive
              Feb 18 '13 at 0:58








            • 2




              @stoive In that case why it's not bb.append(ia)?
              – Mimo
              Feb 18 '13 at 4:13








            • 6




              Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
              – TWright
              Aug 2 '14 at 3:25






            • 1




              @TWright, that's based on this answer.
              – Kenny Evitt
              Oct 13 '14 at 19:52














            423












            423








            423






            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);





            share|improve this answer














            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);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 20 '14 at 23:04

























            answered Feb 24 '11 at 3:50









            Stoive

            8,11642031




            8,11642031








            • 23




              Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
              – syaz
              Feb 22 '12 at 5:36






            • 1




              @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
              – Stoive
              Feb 18 '13 at 0:58








            • 2




              @stoive In that case why it's not bb.append(ia)?
              – Mimo
              Feb 18 '13 at 4:13








            • 6




              Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
              – TWright
              Aug 2 '14 at 3:25






            • 1




              @TWright, that's based on this answer.
              – Kenny Evitt
              Oct 13 '14 at 19:52














            • 23




              Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
              – syaz
              Feb 22 '12 at 5:36






            • 1




              @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
              – Stoive
              Feb 18 '13 at 0:58








            • 2




              @stoive In that case why it's not bb.append(ia)?
              – Mimo
              Feb 18 '13 at 4:13








            • 6




              Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
              – TWright
              Aug 2 '14 at 3:25






            • 1




              @TWright, that's based on this answer.
              – Kenny Evitt
              Oct 13 '14 at 19:52








            23




            23




            Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
            – syaz
            Feb 22 '12 at 5:36




            Why does this always happen... You try to solve a problem for hours upon hours with SO searches here and there. Then you post a question. Within an hour you get the answer from another question. Not that I'm complaining... stackoverflow.com/questions/9388412/…
            – syaz
            Feb 22 '12 at 5:36




            1




            1




            @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
            – Stoive
            Feb 18 '13 at 0:58






            @mimo - It points to the underlying ArrayBuffer, which is then written to the BlobBuilder instance.
            – Stoive
            Feb 18 '13 at 0:58






            2




            2




            @stoive In that case why it's not bb.append(ia)?
            – Mimo
            Feb 18 '13 at 4:13






            @stoive In that case why it's not bb.append(ia)?
            – Mimo
            Feb 18 '13 at 4:13






            6




            6




            Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
            – TWright
            Aug 2 '14 at 3:25




            Just use this: github.com/blueimp/JavaScript-Canvas-to-Blob
            – TWright
            Aug 2 '14 at 3:25




            1




            1




            @TWright, that's based on this answer.
            – Kenny Evitt
            Oct 13 '14 at 19:52




            @TWright, that's based on this answer.
            – Kenny Evitt
            Oct 13 '14 at 19:52













            138














            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'});
            }





            share|improve this answer

















            • 2




              Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
              – DDS
              Mar 14 '13 at 20:28






            • 5




              This doesn't work in Safari.
              – William T.
              Apr 1 '13 at 23:55






            • 2




              Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
              – ObscureRobot
              Apr 10 '13 at 22:29












            • "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
              – Niels Abildgaard
              Jun 16 '14 at 8:42






            • 1




              "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
              – Jasper
              Aug 18 '14 at 10:17


















            138














            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'});
            }





            share|improve this answer

















            • 2




              Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
              – DDS
              Mar 14 '13 at 20:28






            • 5




              This doesn't work in Safari.
              – William T.
              Apr 1 '13 at 23:55






            • 2




              Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
              – ObscureRobot
              Apr 10 '13 at 22:29












            • "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
              – Niels Abildgaard
              Jun 16 '14 at 8:42






            • 1




              "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
              – Jasper
              Aug 18 '14 at 10:17
















            138












            138








            138






            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'});
            }





            share|improve this answer












            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'});
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Aug 14 '12 at 14:19









            vava720

            1,381182




            1,381182








            • 2




              Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
              – DDS
              Mar 14 '13 at 20:28






            • 5




              This doesn't work in Safari.
              – William T.
              Apr 1 '13 at 23:55






            • 2




              Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
              – ObscureRobot
              Apr 10 '13 at 22:29












            • "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
              – Niels Abildgaard
              Jun 16 '14 at 8:42






            • 1




              "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
              – Jasper
              Aug 18 '14 at 10:17
















            • 2




              Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
              – DDS
              Mar 14 '13 at 20:28






            • 5




              This doesn't work in Safari.
              – William T.
              Apr 1 '13 at 23:55






            • 2




              Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
              – ObscureRobot
              Apr 10 '13 at 22:29












            • "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
              – Niels Abildgaard
              Jun 16 '14 at 8:42






            • 1




              "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
              – Jasper
              Aug 18 '14 at 10:17










            2




            2




            Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
            – DDS
            Mar 14 '13 at 20:28




            Just an idea: array=; array.length=binary.length; ... array[i]=bina... etc. So the array is pre-allocated. It saves a push() having to extend the array each iteration, and we're processing possibly millions of items (=bytes) here, so it matters.
            – DDS
            Mar 14 '13 at 20:28




            5




            5




            This doesn't work in Safari.
            – William T.
            Apr 1 '13 at 23:55




            This doesn't work in Safari.
            – William T.
            Apr 1 '13 at 23:55




            2




            2




            Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
            – ObscureRobot
            Apr 10 '13 at 22:29






            Also fails for me on Safari. @WilliamT. 's answer works for Firefox/Safari/Chrome, though.
            – ObscureRobot
            Apr 10 '13 at 22:29














            "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
            – Niels Abildgaard
            Jun 16 '14 at 8:42




            "binary" is a slightly misleading name, as it is not an array of bits, but an array of bytes.
            – Niels Abildgaard
            Jun 16 '14 at 8:42




            1




            1




            "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
            – Jasper
            Aug 18 '14 at 10:17






            "type: 'image/jpeg'" - what if it is a png image OR if you do not know the image extension in advance?
            – Jasper
            Aug 18 '14 at 10:17













            50














            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' });
            }





            share|improve this answer

















            • 10




              Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
              – Per Quested Aronsson
              Sep 23 '13 at 11:09










            • What is with the fallback for iOS6 with webkit prefix? How do you handle this?
              – confile
              Mar 20 '14 at 22:52
















            50














            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' });
            }





            share|improve this answer

















            • 10




              Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
              – Per Quested Aronsson
              Sep 23 '13 at 11:09










            • What is with the fallback for iOS6 with webkit prefix? How do you handle this?
              – confile
              Mar 20 '14 at 22:52














            50












            50








            50






            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' });
            }





            share|improve this answer












            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' });
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Apr 2 '13 at 0:18









            William T.

            9,55134342




            9,55134342








            • 10




              Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
              – Per Quested Aronsson
              Sep 23 '13 at 11:09










            • What is with the fallback for iOS6 with webkit prefix? How do you handle this?
              – confile
              Mar 20 '14 at 22:52














            • 10




              Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
              – Per Quested Aronsson
              Sep 23 '13 at 11:09










            • What is with the fallback for iOS6 with webkit prefix? How do you handle this?
              – confile
              Mar 20 '14 at 22:52








            10




            10




            Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
            – Per Quested Aronsson
            Sep 23 '13 at 11:09




            Great! But you could still keep the mime string dynamic, like in Stoive's solution, I suppose? // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
            – Per Quested Aronsson
            Sep 23 '13 at 11:09












            What is with the fallback for iOS6 with webkit prefix? How do you handle this?
            – confile
            Mar 20 '14 at 22:52




            What is with the fallback for iOS6 with webkit prefix? How do you handle this?
            – confile
            Mar 20 '14 at 22:52











            23














            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
            );





            share|improve this answer



















            • 1




              The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
              – Jakob Kruse
              Jun 10 '15 at 12:37






            • 1




              I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
              – Eric Simonton
              Oct 13 '17 at 13:11










            • i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
              – Martian2049
              Mar 4 '18 at 23:17










            • works in IE 11 also for application/pdf !
              – Michal.S
              Nov 6 '18 at 11:07
















            23














            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
            );





            share|improve this answer



















            • 1




              The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
              – Jakob Kruse
              Jun 10 '15 at 12:37






            • 1




              I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
              – Eric Simonton
              Oct 13 '17 at 13:11










            • i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
              – Martian2049
              Mar 4 '18 at 23:17










            • works in IE 11 also for application/pdf !
              – Michal.S
              Nov 6 '18 at 11:07














            23












            23








            23






            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
            );





            share|improve this answer














            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
            );






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 14 '18 at 0:12









            naXa

            13.2k887132




            13.2k887132










            answered May 26 '15 at 22:51









            cuixiping

            10.9k35170




            10.9k35170








            • 1




              The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
              – Jakob Kruse
              Jun 10 '15 at 12:37






            • 1




              I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
              – Eric Simonton
              Oct 13 '17 at 13:11










            • i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
              – Martian2049
              Mar 4 '18 at 23:17










            • works in IE 11 also for application/pdf !
              – Michal.S
              Nov 6 '18 at 11:07














            • 1




              The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
              – Jakob Kruse
              Jun 10 '15 at 12:37






            • 1




              I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
              – Eric Simonton
              Oct 13 '17 at 13:11










            • i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
              – Martian2049
              Mar 4 '18 at 23:17










            • works in IE 11 also for application/pdf !
              – Michal.S
              Nov 6 '18 at 11:07








            1




            1




            The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
            – Jakob Kruse
            Jun 10 '15 at 12:37




            The polyfill for canvas.toBlob mentioned here is the correct way to handle this issue IMHO.
            – Jakob Kruse
            Jun 10 '15 at 12:37




            1




            1




            I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
            – Eric Simonton
            Oct 13 '17 at 13:11




            I would like to emphasize the last thing in this post: "Now canvas.toBlob() works for all modern browsers."
            – Eric Simonton
            Oct 13 '17 at 13:11












            i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
            – Martian2049
            Mar 4 '18 at 23:17




            i can't believe that my iphone5 doesn't have the api .toBlob .... i'm crying
            – Martian2049
            Mar 4 '18 at 23:17












            works in IE 11 also for application/pdf !
            – Michal.S
            Nov 6 '18 at 11:07




            works in IE 11 also for application/pdf !
            – Michal.S
            Nov 6 '18 at 11:07











            19














            Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer



            function dataURItoBlob(dataURI) {
            'use strict'
            var byteString,
            mimestring

            if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
            byteString = atob(dataURI.split(',')[1])
            } else {
            byteString = decodeURI(dataURI.split(',')[1])
            }

            mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

            var content = new Array();
            for (var i = 0; i < byteString.length; i++) {
            content[i] = byteString.charCodeAt(i)
            }

            return new Blob([new Uint8Array(content)], {type: mimestring});
            }





            share|improve this answer


























              19














              Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer



              function dataURItoBlob(dataURI) {
              'use strict'
              var byteString,
              mimestring

              if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
              byteString = atob(dataURI.split(',')[1])
              } else {
              byteString = decodeURI(dataURI.split(',')[1])
              }

              mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

              var content = new Array();
              for (var i = 0; i < byteString.length; i++) {
              content[i] = byteString.charCodeAt(i)
              }

              return new Blob([new Uint8Array(content)], {type: mimestring});
              }





              share|improve this answer
























                19












                19








                19






                Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer



                function dataURItoBlob(dataURI) {
                'use strict'
                var byteString,
                mimestring

                if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
                byteString = atob(dataURI.split(',')[1])
                } else {
                byteString = decodeURI(dataURI.split(',')[1])
                }

                mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

                var content = new Array();
                for (var i = 0; i < byteString.length; i++) {
                content[i] = byteString.charCodeAt(i)
                }

                return new Blob([new Uint8Array(content)], {type: mimestring});
                }





                share|improve this answer












                Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer



                function dataURItoBlob(dataURI) {
                'use strict'
                var byteString,
                mimestring

                if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
                byteString = atob(dataURI.split(',')[1])
                } else {
                byteString = decodeURI(dataURI.split(',')[1])
                }

                mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

                var content = new Array();
                for (var i = 0; i < byteString.length; i++) {
                content[i] = byteString.charCodeAt(i)
                }

                return new Blob([new Uint8Array(content)], {type: mimestring});
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 18 '13 at 6:33









                Mimo

                3,78542641




                3,78542641























                    19














                    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})
                    })








                    share|improve this answer























                    • what is fetch and how is it relevant?
                      – Ricardo Freitas
                      Nov 28 '16 at 17:33










                    • Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
                      – Endless
                      Nov 28 '16 at 17:49






                    • 1




                      @Endless 'fetch()' a local base64 string... a really clever hack!
                      – Diego ZoracKy
                      Mar 6 '17 at 21:18
















                    19














                    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})
                    })








                    share|improve this answer























                    • what is fetch and how is it relevant?
                      – Ricardo Freitas
                      Nov 28 '16 at 17:33










                    • Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
                      – Endless
                      Nov 28 '16 at 17:49






                    • 1




                      @Endless 'fetch()' a local base64 string... a really clever hack!
                      – Diego ZoracKy
                      Mar 6 '17 at 21:18














                    19












                    19








                    19






                    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})
                    })








                    share|improve this answer














                    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})
                    })








                    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})
                    })





                    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})
                    })






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 1 '17 at 18:48

























                    answered Oct 19 '16 at 20:38









                    Endless

                    11.9k64969




                    11.9k64969












                    • what is fetch and how is it relevant?
                      – Ricardo Freitas
                      Nov 28 '16 at 17:33










                    • Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
                      – Endless
                      Nov 28 '16 at 17:49






                    • 1




                      @Endless 'fetch()' a local base64 string... a really clever hack!
                      – Diego ZoracKy
                      Mar 6 '17 at 21:18


















                    • what is fetch and how is it relevant?
                      – Ricardo Freitas
                      Nov 28 '16 at 17:33










                    • Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
                      – Endless
                      Nov 28 '16 at 17:49






                    • 1




                      @Endless 'fetch()' a local base64 string... a really clever hack!
                      – Diego ZoracKy
                      Mar 6 '17 at 21:18
















                    what is fetch and how is it relevant?
                    – Ricardo Freitas
                    Nov 28 '16 at 17:33




                    what is fetch and how is it relevant?
                    – Ricardo Freitas
                    Nov 28 '16 at 17:33












                    Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
                    – Endless
                    Nov 28 '16 at 17:49




                    Fetch is a modern ajax method that you can use instead of XMLHttpRequest since data url is just a url, You can use ajax to fetch that resource and you got yourself an option to decide if you want it as blob, arraybuffer or text
                    – Endless
                    Nov 28 '16 at 17:49




                    1




                    1




                    @Endless 'fetch()' a local base64 string... a really clever hack!
                    – Diego ZoracKy
                    Mar 6 '17 at 21:18




                    @Endless 'fetch()' a local base64 string... a really clever hack!
                    – Diego ZoracKy
                    Mar 6 '17 at 21:18











                    12














                    The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.



                    I don't see any browser yet supporting it :(



                    Thanks for this great thread!



                    Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):



                        var bb;
                    try {
                    bb = new BlobBuilder();
                    } catch(e) {
                    try {
                    bb = new WebKitBlobBuilder();
                    } catch(e) {
                    bb = new MozBlobBuilder();
                    }
                    }


                    Were you using another library's polyfill for BlobBuilder?






                    share|improve this answer























                    • I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
                      – Stoive
                      Jun 28 '11 at 0:45






                    • 1




                      BlobBuilder seem to be deprecated in favor of Blob
                      – sandstrom
                      Oct 10 '12 at 12:57










                    • BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
                      – Chris Hanson
                      Sep 12 '13 at 18:05










                    • How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
                      – TaylorMac
                      Feb 14 '14 at 19:33


















                    12














                    The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.



                    I don't see any browser yet supporting it :(



                    Thanks for this great thread!



                    Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):



                        var bb;
                    try {
                    bb = new BlobBuilder();
                    } catch(e) {
                    try {
                    bb = new WebKitBlobBuilder();
                    } catch(e) {
                    bb = new MozBlobBuilder();
                    }
                    }


                    Were you using another library's polyfill for BlobBuilder?






                    share|improve this answer























                    • I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
                      – Stoive
                      Jun 28 '11 at 0:45






                    • 1




                      BlobBuilder seem to be deprecated in favor of Blob
                      – sandstrom
                      Oct 10 '12 at 12:57










                    • BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
                      – Chris Hanson
                      Sep 12 '13 at 18:05










                    • How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
                      – TaylorMac
                      Feb 14 '14 at 19:33
















                    12












                    12








                    12






                    The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.



                    I don't see any browser yet supporting it :(



                    Thanks for this great thread!



                    Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):



                        var bb;
                    try {
                    bb = new BlobBuilder();
                    } catch(e) {
                    try {
                    bb = new WebKitBlobBuilder();
                    } catch(e) {
                    bb = new MozBlobBuilder();
                    }
                    }


                    Were you using another library's polyfill for BlobBuilder?






                    share|improve this answer














                    The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.



                    I don't see any browser yet supporting it :(



                    Thanks for this great thread!



                    Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):



                        var bb;
                    try {
                    bb = new BlobBuilder();
                    } catch(e) {
                    try {
                    bb = new WebKitBlobBuilder();
                    } catch(e) {
                    bb = new MozBlobBuilder();
                    }
                    }


                    Were you using another library's polyfill for BlobBuilder?







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 27 '11 at 21:36

























                    answered Jun 27 '11 at 20:39









                    Chris Bosco

                    980816




                    980816












                    • I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
                      – Stoive
                      Jun 28 '11 at 0:45






                    • 1




                      BlobBuilder seem to be deprecated in favor of Blob
                      – sandstrom
                      Oct 10 '12 at 12:57










                    • BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
                      – Chris Hanson
                      Sep 12 '13 at 18:05










                    • How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
                      – TaylorMac
                      Feb 14 '14 at 19:33




















                    • I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
                      – Stoive
                      Jun 28 '11 at 0:45






                    • 1




                      BlobBuilder seem to be deprecated in favor of Blob
                      – sandstrom
                      Oct 10 '12 at 12:57










                    • BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
                      – Chris Hanson
                      Sep 12 '13 at 18:05










                    • How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
                      – TaylorMac
                      Feb 14 '14 at 19:33


















                    I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
                    – Stoive
                    Jun 28 '11 at 0:45




                    I was using Chrome with no polyfills, and don't recall coming across namespacing. I eagerly anticipate canvas.toBlob() - it seems much more appropriate than getAsFile.
                    – Stoive
                    Jun 28 '11 at 0:45




                    1




                    1




                    BlobBuilder seem to be deprecated in favor of Blob
                    – sandstrom
                    Oct 10 '12 at 12:57




                    BlobBuilder seem to be deprecated in favor of Blob
                    – sandstrom
                    Oct 10 '12 at 12:57












                    BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
                    – Chris Hanson
                    Sep 12 '13 at 18:05




                    BlobBuilder is deprecated and this pattern is awful. Better would be : window.BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder); the nested try catches are really ugly and what happens if none of the builders are available?
                    – Chris Hanson
                    Sep 12 '13 at 18:05












                    How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
                    – TaylorMac
                    Feb 14 '14 at 19:33






                    How is this awful? If an exception is thrown and 1) BlobBuilder doesn't exist then nothing happens and the next block is executed. 2) If it does exist, but an exception is thrown then it is deprecated and shouldn't be used anyway, so it continues into the next try block. Ideally you would check if Blob is supported first, and even before this check for toBlob support
                    – TaylorMac
                    Feb 14 '14 at 19:33













                    5














                    var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);


                    can be used without the try catch.



                    Thankx to check_ca. Great work.






                    share|improve this answer



















                    • 1




                      This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
                      – TaylorMac
                      Feb 14 '14 at 19:30
















                    5














                    var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);


                    can be used without the try catch.



                    Thankx to check_ca. Great work.






                    share|improve this answer



















                    • 1




                      This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
                      – TaylorMac
                      Feb 14 '14 at 19:30














                    5












                    5








                    5






                    var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);


                    can be used without the try catch.



                    Thankx to check_ca. Great work.






                    share|improve this answer














                    var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);


                    can be used without the try catch.



                    Thankx to check_ca. Great work.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 29 '12 at 16:32

























                    answered Jan 25 '12 at 20:57









                    Nafis Ahmad

                    1,7051912




                    1,7051912








                    • 1




                      This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
                      – TaylorMac
                      Feb 14 '14 at 19:30














                    • 1




                      This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
                      – TaylorMac
                      Feb 14 '14 at 19:30








                    1




                    1




                    This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
                    – TaylorMac
                    Feb 14 '14 at 19:30




                    This will still throw an error if the browser supports the deprecated BlobBuilder. The browser will use the old method if it supports it, even if it supports the new method. This is not desired, see Chris Bosco's approach below
                    – TaylorMac
                    Feb 14 '14 at 19:30











                    4














                    The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:



                    function dataURItoBlob (dataURI) {
                    // convert base64 to raw binary data held in a string
                    // doesn't handle URLEncoded DataURIs
                    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 an ArrayBuffer
                    var ab = new ArrayBuffer(byteString.length);
                    var ia = new Uint8Array(ab);
                    for (var i = 0; i < byteString.length; i++) {
                    ia[i] = byteString.charCodeAt(i);
                    }

                    // write the ArrayBuffer to a blob, and you're done
                    return new Blob([ab],{type: mimeString});
                    }





                    share|improve this answer


























                      4














                      The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:



                      function dataURItoBlob (dataURI) {
                      // convert base64 to raw binary data held in a string
                      // doesn't handle URLEncoded DataURIs
                      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 an ArrayBuffer
                      var ab = new ArrayBuffer(byteString.length);
                      var ia = new Uint8Array(ab);
                      for (var i = 0; i < byteString.length; i++) {
                      ia[i] = byteString.charCodeAt(i);
                      }

                      // write the ArrayBuffer to a blob, and you're done
                      return new Blob([ab],{type: mimeString});
                      }





                      share|improve this answer
























                        4












                        4








                        4






                        The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:



                        function dataURItoBlob (dataURI) {
                        // convert base64 to raw binary data held in a string
                        // doesn't handle URLEncoded DataURIs
                        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 an ArrayBuffer
                        var ab = new ArrayBuffer(byteString.length);
                        var ia = new Uint8Array(ab);
                        for (var i = 0; i < byteString.length; i++) {
                        ia[i] = byteString.charCodeAt(i);
                        }

                        // write the ArrayBuffer to a blob, and you're done
                        return new Blob([ab],{type: mimeString});
                        }





                        share|improve this answer












                        The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:



                        function dataURItoBlob (dataURI) {
                        // convert base64 to raw binary data held in a string
                        // doesn't handle URLEncoded DataURIs
                        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 an ArrayBuffer
                        var ab = new ArrayBuffer(byteString.length);
                        var ia = new Uint8Array(ab);
                        for (var i = 0; i < byteString.length; i++) {
                        ia[i] = byteString.charCodeAt(i);
                        }

                        // write the ArrayBuffer to a blob, and you're done
                        return new Blob([ab],{type: mimeString});
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 16 '13 at 17:14









                        topkara

                        680615




                        680615























                            3














                            Here is an ES6 version of Stoive's answer:



                            export class ImageDataConverter {
                            constructor(dataURI) {
                            this.dataURI = dataURI;
                            }

                            getByteString() {
                            let byteString;
                            if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
                            byteString = atob(this.dataURI.split(',')[1]);
                            } else {
                            byteString = decodeURI(this.dataURI.split(',')[1]);
                            }
                            return byteString;
                            }

                            getMimeString() {
                            return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
                            }

                            convertToTypedArray() {
                            let byteString = this.getByteString();
                            let ia = new Uint8Array(byteString.length);
                            for (let i = 0; i < byteString.length; i++) {
                            ia[i] = byteString.charCodeAt(i);
                            }
                            return ia;
                            }

                            dataURItoBlob() {
                            let mimeString = this.getMimeString();
                            let intArray = this.convertToTypedArray();
                            return new Blob([intArray], {type: mimeString});
                            }
                            }


                            Usage:



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





                            share|improve this answer




























                              3














                              Here is an ES6 version of Stoive's answer:



                              export class ImageDataConverter {
                              constructor(dataURI) {
                              this.dataURI = dataURI;
                              }

                              getByteString() {
                              let byteString;
                              if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
                              byteString = atob(this.dataURI.split(',')[1]);
                              } else {
                              byteString = decodeURI(this.dataURI.split(',')[1]);
                              }
                              return byteString;
                              }

                              getMimeString() {
                              return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
                              }

                              convertToTypedArray() {
                              let byteString = this.getByteString();
                              let ia = new Uint8Array(byteString.length);
                              for (let i = 0; i < byteString.length; i++) {
                              ia[i] = byteString.charCodeAt(i);
                              }
                              return ia;
                              }

                              dataURItoBlob() {
                              let mimeString = this.getMimeString();
                              let intArray = this.convertToTypedArray();
                              return new Blob([intArray], {type: mimeString});
                              }
                              }


                              Usage:



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





                              share|improve this answer


























                                3












                                3








                                3






                                Here is an ES6 version of Stoive's answer:



                                export class ImageDataConverter {
                                constructor(dataURI) {
                                this.dataURI = dataURI;
                                }

                                getByteString() {
                                let byteString;
                                if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
                                byteString = atob(this.dataURI.split(',')[1]);
                                } else {
                                byteString = decodeURI(this.dataURI.split(',')[1]);
                                }
                                return byteString;
                                }

                                getMimeString() {
                                return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
                                }

                                convertToTypedArray() {
                                let byteString = this.getByteString();
                                let ia = new Uint8Array(byteString.length);
                                for (let i = 0; i < byteString.length; i++) {
                                ia[i] = byteString.charCodeAt(i);
                                }
                                return ia;
                                }

                                dataURItoBlob() {
                                let mimeString = this.getMimeString();
                                let intArray = this.convertToTypedArray();
                                return new Blob([intArray], {type: mimeString});
                                }
                                }


                                Usage:



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





                                share|improve this answer














                                Here is an ES6 version of Stoive's answer:



                                export class ImageDataConverter {
                                constructor(dataURI) {
                                this.dataURI = dataURI;
                                }

                                getByteString() {
                                let byteString;
                                if (this.dataURI.split(',')[0].indexOf('base64') >= 0) {
                                byteString = atob(this.dataURI.split(',')[1]);
                                } else {
                                byteString = decodeURI(this.dataURI.split(',')[1]);
                                }
                                return byteString;
                                }

                                getMimeString() {
                                return this.dataURI.split(',')[0].split(':')[1].split(';')[0];
                                }

                                convertToTypedArray() {
                                let byteString = this.getByteString();
                                let ia = new Uint8Array(byteString.length);
                                for (let i = 0; i < byteString.length; i++) {
                                ia[i] = byteString.charCodeAt(i);
                                }
                                return ia;
                                }

                                dataURItoBlob() {
                                let mimeString = this.getMimeString();
                                let intArray = this.convertToTypedArray();
                                return new Blob([intArray], {type: mimeString});
                                }
                                }


                                Usage:



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






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited May 23 '17 at 12:26









                                Community

                                11




                                11










                                answered Oct 18 '16 at 17:18









                                vekerdyb

                                392312




                                392312























                                    1














                                    make it simple :D



                                    function dataURItoBlob(dataURI,mime) {
                                    // convert base64 to raw binary data held in a string
                                    // doesn't handle URLEncoded DataURIs

                                    var byteString = window.atob(dataURI);

                                    // separate out the mime component


                                    // write the bytes of the string to an ArrayBuffer
                                    //var ab = new ArrayBuffer(byteString.length);
                                    var ia = new Uint8Array(byteString.length);
                                    for (var i = 0; i < byteString.length; i++) {
                                    ia[i] = byteString.charCodeAt(i);
                                    }

                                    // write the ArrayBuffer to a blob, and you're done
                                    var blob = new Blob([ia], { type: mime });

                                    return blob;
                                    }





                                    share|improve this answer


























                                      1














                                      make it simple :D



                                      function dataURItoBlob(dataURI,mime) {
                                      // convert base64 to raw binary data held in a string
                                      // doesn't handle URLEncoded DataURIs

                                      var byteString = window.atob(dataURI);

                                      // separate out the mime component


                                      // write the bytes of the string to an ArrayBuffer
                                      //var ab = new ArrayBuffer(byteString.length);
                                      var ia = new Uint8Array(byteString.length);
                                      for (var i = 0; i < byteString.length; i++) {
                                      ia[i] = byteString.charCodeAt(i);
                                      }

                                      // write the ArrayBuffer to a blob, and you're done
                                      var blob = new Blob([ia], { type: mime });

                                      return blob;
                                      }





                                      share|improve this answer
























                                        1












                                        1








                                        1






                                        make it simple :D



                                        function dataURItoBlob(dataURI,mime) {
                                        // convert base64 to raw binary data held in a string
                                        // doesn't handle URLEncoded DataURIs

                                        var byteString = window.atob(dataURI);

                                        // separate out the mime component


                                        // write the bytes of the string to an ArrayBuffer
                                        //var ab = new ArrayBuffer(byteString.length);
                                        var ia = new Uint8Array(byteString.length);
                                        for (var i = 0; i < byteString.length; i++) {
                                        ia[i] = byteString.charCodeAt(i);
                                        }

                                        // write the ArrayBuffer to a blob, and you're done
                                        var blob = new Blob([ia], { type: mime });

                                        return blob;
                                        }





                                        share|improve this answer












                                        make it simple :D



                                        function dataURItoBlob(dataURI,mime) {
                                        // convert base64 to raw binary data held in a string
                                        // doesn't handle URLEncoded DataURIs

                                        var byteString = window.atob(dataURI);

                                        // separate out the mime component


                                        // write the bytes of the string to an ArrayBuffer
                                        //var ab = new ArrayBuffer(byteString.length);
                                        var ia = new Uint8Array(byteString.length);
                                        for (var i = 0; i < byteString.length; i++) {
                                        ia[i] = byteString.charCodeAt(i);
                                        }

                                        // write the ArrayBuffer to a blob, and you're done
                                        var blob = new Blob([ia], { type: mime });

                                        return blob;
                                        }






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Sep 7 '14 at 19:16









                                        Sendy

                                        1614




                                        1614























                                            0














                                            Thanks! @steovi for this solution.



                                            I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).



                                            converterDataURItoBlob(dataURI) {
                                            let byteString;
                                            let mimeString;
                                            let ia;

                                            if (dataURI.split(',')[0].indexOf('base64') >= 0) {
                                            byteString = atob(dataURI.split(',')[1]);
                                            } else {
                                            byteString = encodeURI(dataURI.split(',')[1]);
                                            }
                                            // separate out the mime component
                                            mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                                            // write the bytes of the string to a typed array
                                            ia = new Uint8Array(byteString.length);
                                            for (var i = 0; i < byteString.length; i++) {
                                            ia[i] = byteString.charCodeAt(i);
                                            }
                                            return new Blob([ia], {type:mimeString});
                                            }





                                            share|improve this answer




























                                              0














                                              Thanks! @steovi for this solution.



                                              I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).



                                              converterDataURItoBlob(dataURI) {
                                              let byteString;
                                              let mimeString;
                                              let ia;

                                              if (dataURI.split(',')[0].indexOf('base64') >= 0) {
                                              byteString = atob(dataURI.split(',')[1]);
                                              } else {
                                              byteString = encodeURI(dataURI.split(',')[1]);
                                              }
                                              // separate out the mime component
                                              mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                                              // write the bytes of the string to a typed array
                                              ia = new Uint8Array(byteString.length);
                                              for (var i = 0; i < byteString.length; i++) {
                                              ia[i] = byteString.charCodeAt(i);
                                              }
                                              return new Blob([ia], {type:mimeString});
                                              }





                                              share|improve this answer


























                                                0












                                                0








                                                0






                                                Thanks! @steovi for this solution.



                                                I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).



                                                converterDataURItoBlob(dataURI) {
                                                let byteString;
                                                let mimeString;
                                                let ia;

                                                if (dataURI.split(',')[0].indexOf('base64') >= 0) {
                                                byteString = atob(dataURI.split(',')[1]);
                                                } else {
                                                byteString = encodeURI(dataURI.split(',')[1]);
                                                }
                                                // separate out the mime component
                                                mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                                                // write the bytes of the string to a typed array
                                                ia = new Uint8Array(byteString.length);
                                                for (var i = 0; i < byteString.length; i++) {
                                                ia[i] = byteString.charCodeAt(i);
                                                }
                                                return new Blob([ia], {type:mimeString});
                                                }





                                                share|improve this answer














                                                Thanks! @steovi for this solution.



                                                I have added support to ES6 version and changed from unescape to dataURI(unescape is deprecated).



                                                converterDataURItoBlob(dataURI) {
                                                let byteString;
                                                let mimeString;
                                                let ia;

                                                if (dataURI.split(',')[0].indexOf('base64') >= 0) {
                                                byteString = atob(dataURI.split(',')[1]);
                                                } else {
                                                byteString = encodeURI(dataURI.split(',')[1]);
                                                }
                                                // separate out the mime component
                                                mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

                                                // write the bytes of the string to a typed array
                                                ia = new Uint8Array(byteString.length);
                                                for (var i = 0; i < byteString.length; i++) {
                                                ia[i] = byteString.charCodeAt(i);
                                                }
                                                return new Blob([ia], {type:mimeString});
                                                }






                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Apr 9 '18 at 16:12









                                                crabbly

                                                3,2421824




                                                3,2421824










                                                answered Apr 2 '18 at 18:07









                                                wilfredonoyola

                                                767




                                                767























                                                    -1














                                                    toDataURL gives you a string and you can put that string to a hidden input.






                                                    share|improve this answer





















                                                    • Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
                                                      – Stoive
                                                      Feb 24 '11 at 3:11










                                                    • This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
                                                      – Lucky
                                                      Mar 30 '15 at 8:31
















                                                    -1














                                                    toDataURL gives you a string and you can put that string to a hidden input.






                                                    share|improve this answer





















                                                    • Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
                                                      – Stoive
                                                      Feb 24 '11 at 3:11










                                                    • This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
                                                      – Lucky
                                                      Mar 30 '15 at 8:31














                                                    -1












                                                    -1








                                                    -1






                                                    toDataURL gives you a string and you can put that string to a hidden input.






                                                    share|improve this answer












                                                    toDataURL gives you a string and you can put that string to a hidden input.







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Feb 23 '11 at 14:19









                                                    Cat Chen

                                                    2,1431210




                                                    2,1431210












                                                    • Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
                                                      – Stoive
                                                      Feb 24 '11 at 3:11










                                                    • This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
                                                      – Lucky
                                                      Mar 30 '15 at 8:31


















                                                    • Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
                                                      – Stoive
                                                      Feb 24 '11 at 3:11










                                                    • This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
                                                      – Lucky
                                                      Mar 30 '15 at 8:31
















                                                    Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
                                                    – Stoive
                                                    Feb 24 '11 at 3:11




                                                    Could you please give an example? I don't wan't to upload a base64 string (which is what doing <input type=hidden value="data:..." /> would do), I want to upload the file data (like what <input type="file" /> does, except you're not allowed to set the value property on these).
                                                    – Stoive
                                                    Feb 24 '11 at 3:11












                                                    This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
                                                    – Lucky
                                                    Mar 30 '15 at 8:31




                                                    This should be a comment rather than an answer. Please elaborate the answer with proper explanation. @Cat Chen
                                                    – Lucky
                                                    Mar 30 '15 at 8:31











                                                    -4














                                                    I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:



                                                    var dataURL = canvas.toDataURL("image/jpeg");

                                                    var name = "image.jpg";
                                                    var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});





                                                    share|improve this answer



















                                                    • 2




                                                      Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
                                                      – Pierre Maoui
                                                      Jul 7 '16 at 14:44






                                                    • 2




                                                      WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
                                                      – Ravinder Payal
                                                      Jul 19 '16 at 18:52










                                                    • That is coolest answer I have ever seen, LOL
                                                      – Humoyun
                                                      Oct 4 '18 at 5:09
















                                                    -4














                                                    I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:



                                                    var dataURL = canvas.toDataURL("image/jpeg");

                                                    var name = "image.jpg";
                                                    var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});





                                                    share|improve this answer



















                                                    • 2




                                                      Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
                                                      – Pierre Maoui
                                                      Jul 7 '16 at 14:44






                                                    • 2




                                                      WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
                                                      – Ravinder Payal
                                                      Jul 19 '16 at 18:52










                                                    • That is coolest answer I have ever seen, LOL
                                                      – Humoyun
                                                      Oct 4 '18 at 5:09














                                                    -4












                                                    -4








                                                    -4






                                                    I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:



                                                    var dataURL = canvas.toDataURL("image/jpeg");

                                                    var name = "image.jpg";
                                                    var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});





                                                    share|improve this answer














                                                    I had exactly the same problem as Ravinder Payal, and I've found the answer. Try this:



                                                    var dataURL = canvas.toDataURL("image/jpeg");

                                                    var name = "image.jpg";
                                                    var parseFile = new Parse.File(name, {base64: dataURL.substring(23)});






                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Aug 30 '14 at 17:28









                                                    Spooky

                                                    2,52472036




                                                    2,52472036










                                                    answered Aug 30 '14 at 16:31









                                                    feng

                                                    332




                                                    332








                                                    • 2




                                                      Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
                                                      – Pierre Maoui
                                                      Jul 7 '16 at 14:44






                                                    • 2




                                                      WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
                                                      – Ravinder Payal
                                                      Jul 19 '16 at 18:52










                                                    • That is coolest answer I have ever seen, LOL
                                                      – Humoyun
                                                      Oct 4 '18 at 5:09














                                                    • 2




                                                      Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
                                                      – Pierre Maoui
                                                      Jul 7 '16 at 14:44






                                                    • 2




                                                      WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
                                                      – Ravinder Payal
                                                      Jul 19 '16 at 18:52










                                                    • That is coolest answer I have ever seen, LOL
                                                      – Humoyun
                                                      Oct 4 '18 at 5:09








                                                    2




                                                    2




                                                    Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
                                                    – Pierre Maoui
                                                    Jul 7 '16 at 14:44




                                                    Are you really suggesting to use Parse.com ? You should mention that your answer require dependencies !
                                                    – Pierre Maoui
                                                    Jul 7 '16 at 14:44




                                                    2




                                                    2




                                                    WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
                                                    – Ravinder Payal
                                                    Jul 19 '16 at 18:52




                                                    WTF ? Why any one will upload base64 code of image to PARSE server and then download?When we can directly upload base64 on our servers and main thing is that it takes same data to upload base64 string or image file. And if you just want to alow user to download the image , you can use this window.open(canvas.toDataURL("image/jpeg"))
                                                    – Ravinder Payal
                                                    Jul 19 '16 at 18:52












                                                    That is coolest answer I have ever seen, LOL
                                                    – Humoyun
                                                    Oct 4 '18 at 5:09




                                                    That is coolest answer I have ever seen, LOL
                                                    – Humoyun
                                                    Oct 4 '18 at 5:09


















                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.





                                                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                    Please pay close attention to the following guidance:


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4998908%2fconvert-data-uri-to-file-then-append-to-formdata%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    Guess what letter conforming each word

                                                    Port of Spain

                                                    Run scheduled task as local user group (not BUILTIN)