无法在“窗口”上执行“btoa”:要编码的string包含Latin1范围之外的字符。

根据我的testing,标题中的错误仅在Google Chrome中引发。 我是base64编码一个大的XML文件,以便它可以下载:

this.loader.src = "data:application/x-forcedownload;base64,"+ btoa("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +"<"+this.gamesave.tagName+">" +this.xml.firstChild.innerHTML +"</"+this.gamesave.tagName+">"); 

this.loader是隐藏的iframe。

这个错误实际上是一个很大的改变,因为通常谷歌浏览器会在btoa调用中崩溃。 Mozilla Firefox在这里没有问题,所以问题是与浏览器有关。 我不知道文件中有任何奇怪的字符。 其实我相信没有非ascii字符。

问:如何查找有问题的字符并将其replace,以便Chrome停止投诉?

我试图使用Downloadify来启动下载,但它不起作用。 这是不可靠的,抛出错误,允许debugging。

如果你有UTF8,使用这个(实际上适用于SVG源),如:

 btoa(unescape(encodeURIComponent(str))) 

例:

  var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup))); var img = new Image(1, 1); // width, height values are optional params img.src = imgsrc; 

如果你需要解码base64,使用这个:

 var str2 = decodeURIComponent(escape(window.atob(b64))); console.log(str2); 

例:

 var str = "äöüÄÖÜçéèñ"; var b64 = window.btoa(unescape(encodeURIComponent(str))) console.log(b64); var str2 = decodeURIComponent(escape(window.atob(b64))); console.log(str2); 

注意:如果您需要在mobile-safari中使用此function,则可能需要从base64数据中去除所有空白区域…

 function b64_to_utf8( str ) { str = str.replace(/\s/g, ''); return decodeURIComponent(escape(window.atob( str ))); } 

2017更新

这个问题一直困扰着我。
简单的事实是,atob并不真正处理UTF8string – 它只是ASCII。
另外,我不会使用像英国石油公司的base64这样的英国媒体报道。
但webtoolkit确实有一个小巧,漂亮,可维护的实现:

 /** * * Base64 encode / decode * http://www.webtoolkit.info * **/ var Base64 = { // private property _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" // public method for encoding , encode: function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } // Whend return output; } // End Function encode // public method for decoding ,decode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } // Whend output = Base64._utf8_decode(output); return output; } // End Function decode // private method for UTF-8 encoding ,_utf8_encode: function (string) { var utftext = ""; string = string.replace(/\r\n/g, "\n"); for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } // Next n return utftext; } // End Function _utf8_encode // private method for UTF-8 decoding ,_utf8_decode: function (utftext) { var string = ""; var i = 0; var c, c1, c2, c3; c = c1 = c2 = 0; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } // Whend return string; } // End Function _utf8_decode } 

我只是认为我应该分享我是如何解决问题的,为什么我认为这是正确的解决scheme(假设您没有针对旧版浏览器进行优化)。

将数据转换为dataURL( data: ...

 var blob = new Blob( // I'm using page innerHTML as data // note that you can use the array // to concatenate many long strings EFFICIENTLY [document.body.innerHTML], // Mime type is important for data url {type : 'text/html'} ); // This FileReader works asynchronously, so it doesn't lag // the web application var a = new FileReader(); a.onload = function(e) { // Capture result here console.log(e.target.result); }; a.readAsDataURL(blob); 

允许用户保存数据

除了明显的解决scheme – 打开一个新的窗口与您的dataURL作为URL你可以做另外两件事情。

1.使用fileSaver.js

文件保护程序可以用预定义的文件名创build实际的fileSave对话框。 它也可以回退到正常的dataURL方法。

2.使用(实验) URL.createObjectURL

这对于重用base64编码数据非常有用。 它为你的dataURL创build一个简短的URL:

 console.log(URL.createObjectURL(blob)); //Prints: blob:http://stackoverflow.com/7c18953f-f5f8-41d2-abf5-e9cbced9bc42 

不要忘记使用包含前导blob前缀的URL。 我再次使用document.body

图片描述

您可以使用这个简短的URL作为AJAX目标, <script>源或<a> href位置。 您有责任销毁该url:

 URL.revokeObjectURL('blob:http://stackoverflow.com/7c18953f-f5f8-41d2-abf5-e9cbced9bc42') 

unescapeencodeURIComponent使用btoa不适合我。 用XML / HTML实体replace所有特殊的caracteres,然后转换为base64表示是解决这个问题的唯一方法。 一些代码:

 base64 = btoa(str.replace(/[\u00A0-\u2666]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; })); 

使用库来代替

我们不必重新发明轮子。 只需使用图书馆来节省时间和头痛。

JS-的base64

https://github.com/dankogai/js-base64是好的,我确认它支持unicode非常好。;

 Base64.encode('dankogai'); // ZGFua29nYWk= Base64.encode('小飼弾'); // 5bCP6aO85by+ Base64.encodeURI('小飼弾'); // 5bCP6aO85by- Base64.decode('ZGFua29nYWk='); // dankogai Base64.decode('5bCP6aO85by+'); // 小飼弾// note .decodeURI() is unnecessary since it accepts both flavors Base64.decode('5bCP6aO85by-'); // 小飼弾 

我自己也遇到了这个问题。

首先,稍微修改你的代码:

 var download = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +"<"+this.gamesave.tagName+">" +this.xml.firstChild.innerHTML +"</"+this.gamesave.tagName+">"; this.loader.src = "data:application/x-forcedownload;base64,"+ btoa(download); 

然后使用你最喜欢的Web检查器,在指定this.loader.src的代码行上放置一个断点,然后执行下面的代码:

 for (var i = 0; i < download.length; i++) { if (download[i].charCodeAt(0) > 255) { console.warn('found character ' + download[i].charCodeAt(0) + ' "' + download[i] + '" at position ' + i); } } 

根据您的应用程序,replace超出范围的字符可能会或可能不会工作,因为您将修改数据。 使用btoa方法查看MDN关于unicode字符的注释:

https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

作为Stefan Steiger的补充答案:(因为它看起来不好看)

扩展string原型:

 String.prototype.b64encode = function() { return btoa(unescape(encodeURIComponent(this))); }; String.prototype.b64decode = function() { return decodeURIComponent(escape(atob(this))); }; 

用法:

 var str = "äöüÄÖÜçéèñ"; var encoded = str.b64encode(); console.log( encoded.b64decode() );