Invalid character error while using atob() method
Asked Answered
T

2

5

I have read a question in stack overflow with this code work in IE 10 but not work in ie9,

but still I am facing issue on this.

var image = canvas.toDataURL();
image = image.replace(/^data:[a-z]*;,/, '');
var byteString = atob(image);
var buffer = new ArrayBuffer(byteString.length);
var intArray = new Uint8Array(buffer);
for (var i = 0; i < byteString.length; i++) {
    intArray[i] = byteString.charCodeAt(i);
}
blob = new Blob([buffer], {type: "image/png"});
window.navigator.msSaveOrOpenBlob(blob, "test.png");

while converting atob(image) it throw an exception 0x800a139e - JavaScript runtime error: InvalidCharacterError I tried several things but nothing works...

I got this in image variable

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcIAAAGQCAYAAAA9XmC5AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAABJFSURBVHhe7dvPa5x3fsDxeaR0l3UO9dLuSnJLE3rpzc6pp0KUQ2MLL8Xk1BZWt+7BhmKaGYctfKR3ng8vjyZTE6W5St98PZnF9ZO/NeZsiyWt0+c//RUWQBHxIkQjlBGsEx7Eb/7ZbqQF23zz22vvf+L6+f/Um4BQDeNRqPtvMoy194TQsc5EcIRatv2SZnmY9L1HOOUuDPdADpJCOEIRfQex7BaviCzkXsRxwc5At3kyzJwxMoXZmZfdLnZ7/c3yxwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvkF6vf8DAs32KwowBEUAAAAASUVORK5CYII=

please help me.. Thanks in advance..

Thalamus answered 27/10, 2014 at 11:19 Comment(0)
S
7

1) your base64 encoded string probably is not fully valid. you can try to use this code instead of atob

var decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

2) I think it should be image = image.replace(/^[^,]+,/, '');

3) As far as I know, support of the Blob in IE starts from version 10 - https://developer.mozilla.org/en-US/docs/Web/API/Blob

Surcingle answered 28/10, 2014 at 4:50 Comment(2)
In that String i just remove this and it works for me..data:image/png;base64, Any way great thanks to you.. this is too working fine..Yes i know blob is not supported by IE 9 and below. Do we have any other choice for IE 9 and below?Thalamus
@Thalamus this is what image = image.replace(/^[^,]+,/, ''); is doingSurcingle
D
3

In case someone reachs this and the image = image.replace(/^[^,]+,/, ''); solution doesn't work for them, I got the same error calling atob function in IE11.

In my case, the error was caused because the base64 string had a carriage return each 76 characters.

This wasn't a problem for Chrome or Firefox, but IE11 produced the InvalidCharacterError.

b64Data = b64Data.replace(/\r\n/g, ''); solved my problem.

Dotty answered 21/6, 2019 at 11:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.