Convert array buffer to string - call stack size exceeded

Our application downloads a zip file, but the answer is in binary format.

So, I did to convert it to base64. It works when the size 87.7KB, but an error occurs when the size of the response 183KB.

Error Uncaught RangeError: Maximum call stack size exceeded

Matching line

btoa(String.fromCharCode.apply(null, new Uint8Array(blob)))

In accordance with this answer String.fromCharCode.apply() must be replaced by TextEncoder.

So, I changed it to

btoa(new TextDecoder('utf-8').decode(new Uint8Array(blob)))

but I get an error.

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

I changed it again using the topmost snippet of this.

New code now

btoa(unescape(encodeURIComponent(new TextDecoder('utf-8').decode(new Uint8Array(blob)))))

The download now works, but the download zip file is corrupt.

All code can be seen here.

+5
source share
3 answers

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

+20

pemision , Chrome, Sulusion IE

@iamdevlinph ?

0

fooobar.com/questions/211327 / ...

function blobToB64(data) {
    if ('TextDecoder' in window) {
      // Decode as UTF-8
      var dataView = new DataView(data);
      var decoder = new TextDecoder('utf8');
      return btoa(decoder.decode(dataView));
    } else {
      // Fallback
      return btoa(new Uint8Array(data).reduce((data, byte) =>
        data + String.fromCharCode(byte),
        ''))
    }
}

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

This one seems to have better performance.

-1
source

Source: https://habr.com/ru/post/1648228/


All Articles