9

I use XMLHttpRequest to generate Blob from data URI using this code:

function dataUrlToBlob(dataUrl, callback) {
    var xhr = new XMLHttpRequest;
    xhr.open( 'GET',  dataUrl);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        callback( new Blob( [this.response], {type: 'image/png'} ) );
    };
    xhr.send();
}

Usage:

dataUrlToBlob('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=', callback);

Everything works fine in every browser except Safari. It throws such an error:

[Error] XMLHttpRequest cannot load data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQIW2NkAAIAAAoAAggA9GkAAAAASUVORK5CYII=. Cross origin requests are only supported for HTTP.

The question is, are there any ways to make this approach working in Safari?

artch
  • 4,487
  • 2
  • 28
  • 35

1 Answers1

-2

Why would you use an XHR to do that? Just do it synchronously (answer taken from here):

function dataURItoBlob(dataURI) {
    if(typeof dataURI !== 'string'){
        throw new Error('Invalid argument: dataURI must be a string');
    }
    dataURI = dataURI.split(',');
    var type = dataURI[0].split(':')[1].split(';')[0],
        byteString = atob(dataURI[1]),
        byteStringLength = byteString.length,
        arrayBuffer = new ArrayBuffer(byteStringLength),
        intArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteStringLength; i++) {
        intArray[i] = byteString.charCodeAt(i);
    }
    return new Blob([intArray], {
        type: type
    });
}
Community
  • 1
  • 1
idbehold
  • 16,833
  • 5
  • 47
  • 74
  • I know that. But asynchronously is faster. That is not the question here. – artch Jun 19 '15 at 04:37
  • @artch an asynchronous function will **always** be slower than a synchronous function doing the same thing. – idbehold Jun 19 '15 at 14:55
  • 4
    Please don't start polemic about that. You don't know our exact use case, so it's just meaningless. XHR is capable to make use of multiple cores in parallel on some systems, so that in many concurrent operations environment it is **much** faster than the synchronous impementation using the same single JS process (or even using web workers, since they have messaging overhead). – artch Jun 20 '15 at 00:25