将数组缓冲区转换为字符串 - 超出了最大调用堆栈大小

iam*_*nph 5 javascript binary

我们的应用程序下载了一个zip文件,但响应是二进制的.

所以我做的是将其转换为base64.它适用于大小87.7KB但响应大小为时发生错误183KB.

错误是 Uncaught RangeError: Maximum call stack size exceeded

这条线是

btoa(String.fromCharCode.apply(null, new Uint8Array(blob)))
Run Code Online (Sandbox Code Playgroud)

根据这个答案,String.fromCharCode.apply()必须更换TextEncoder.

所以我改成了

btoa(new TextDecoder('utf-8').decode(new Uint8Array(blob)))
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误.

Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

我使用此答案的最顶部片段再次更改了它

新代码现在

btoa(unescape(encodeURIComponent(new TextDecoder('utf-8').decode(new Uint8Array(blob)))))
Run Code Online (Sandbox Code Playgroud)

下载现在可以使用,但下载zip文件已损坏.

整个代码可以在这里看到

iam*_*nph 21

我从另一个问题得到了答案

btoa(new Uint8Array(blob).reduce(function (data, byte) {
    return data + String.fromCharCode(byte);
}, ''));
Run Code Online (Sandbox Code Playgroud)

资源