Kingsley Simon
Kingsley Simon

Reputation: 2210

Illegal Constructor error: convert Base64 to Blob fails on cordova

I want to convert my Base64 image to a blob in my cordova app project using AngularJS but i keep getting Illegal constructor error. I have tried a lot of the solutions given online but none seems to be working. Any help is appreciated.

var imageElement = angular.element(document.querySelector('#profileImg'));
var imageURI = dataURIToBlobURI(imageElement.attr('src'));

 function dataURIToBlobURI(dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    var byteString = atob(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);
    }

    var bb = new Blob([ab], {type: 'image/png'});
    return bb;
  }

I keep getting an error over here new Blob([ab], {type: 'image/png'}) and dont seem to knw how to make it work. Only happens when the app is in Android or iOS not when viewed in Chrome.

I have tried the following but all to no avail.

var bb = new Blob(ab);
var bb = new Blob([ab]);
var bb = new Blob(dataURI); 

Thanks

Upvotes: 1

Views: 568

Answers (2)

Kingsley Simon
Kingsley Simon

Reputation: 2210

I used this to solve my problem. Just incase anyone runs into this problem. All solutions didnt work for me on my device. Just follow instructions and add the javascript file and you shud be fine. https://github.com/blueimp/JavaScript-Canvas-to-Blob

var b64Data = 'R0lGODdhUAA8AIABAAAAAP///ywAAAAAUAA8AAACS4SPqcvtD6' +
        'OctNqLs968+w+G4kiW5omm6sq27gvH8kzX9o3n+s73/g8MCofE' +
        'ovGITCqXzKbzCY1Kp9Sq9YrNarfcrvcLDovH5PKsAAA7',
    imageUrl = 'data:image/gif;base64,' + b64Data,
    blob = window.dataURLtoBlob && window.dataURLtoBlob(imageUrl);

Upvotes: 0

Vlad Dekhanov
Vlad Dekhanov

Reputation: 1084

Kingsley! Possible, device where you could reproduce the error doesn't support Blob actually. Actually you could use two ways:

Firstly, check polyfill or smth similar to fix your problem. It will allow you to use Blob as a constructor.

Secondly, you could use BlobBuilder except of Blob. Small exmaple below,

var bb = new BlobBuilder();
bb.append('blob content');
var blob = bb.getBlob('text/plain');

Upvotes: 1

Related Questions