我正在使用对perl脚本的JAX调用,该脚本返回pdf的base64,但它在IE中给我带来了麻烦。最终,我想解码base64数据并创建一个用于PDFJS的blob。它适用于chrome / firefox,代码如下:
$.ajax({
url: '/path/to/my.cgi',
type: "POST",
data: opts,
async: false,
success: function(data){
var byteChars = atob(data);
var byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++){
byteNumbers[i] = byteChars.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type: "application/pdf;base64" });
var url = URL.createObjectURL(blob);
}
});
但是,它永远不会超过var byteChars = atob(data)
。我的印象是它应该在&gt; IE10中工作,但我继续前进并决定尝试this question的代码。出于某种原因,它正在用一些中文/普通话字符解码base64。以下是IE11和chrome的结果:
我已尝试过来自其他位置的base64脚本,例如this,但结果在IE中始终相同。这不允许PDFJS正确加载blob。
如果有人能说清楚,我会很感激。这是我的最新代码:
$.ajax({
...
success: function(data){
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
var byteChars;
if(userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident/)){
// You can use either link I provided for this Base64.decode()
byteChars = Base64.decode(data);
} else {
byteChars = atob(data);
}
var byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++){
byteNumbers[i] = byteChars.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type: "application/pdf;base64" });
var url = URL.createObjectURL(blob);
}
});
答案 0 :(得分:0)
好的,出于某种原因我遇到了base64库的问题。所以,我只使用以下功能来替换atob,它在IE,iOS,Firefox,Chrome,Android和Edge中运行良好。
var atob = function(input){
var str = String(input).replace(/=+$/, '');
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}