0

I can demonstrate my issue with this simple code:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <input type="file" name="fileSelector" id="fileSelector" onchange="imageSelected(this)" accept=".png, .jpg, .jpeg, .webp" multiple>
    
</body>
</html>

JS:

function bufferToBase64(buffer){
    return encodeURIComponent(btoa(String.fromCharCode(...new Uint8Array(buffer))));
}


async function imageSelected(input){
    for (let i = 0; i < input.files.length; i++) {
        let file = input.files[i];
        let buffer = await file.arrayBuffer();
        console.log(file);
        console.log(buffer);
        console.log(bufferToBase64(buffer));

        //.......remaining stuff
    }
}

The above works fine for smaller files (I tested with a 300KB file for example).

However, when I select a file which is 650KB, it throws the error:

Uncaught (in promise) RangeError: too many function arguments

enter image description here

You can test this with any image which is slightly bigger. This 2.6MB image will fail for example:

https://i.imgur.com/kEopYvf.png

I am not really sure what I am doing wrong? Is there a size limit?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • `String.fromCharCode(...new Uint8Array(buffer))` — Do you know what `...` does in that expression? – Quentin Aug 08 '23 at 07:59
  • You are simply passing more arguments to the method via the spread operator there, than the browser can handle. The limits differ between implementations - https://stackoverflow.com/a/22747272/1427878 So you will have to do this in smaller chunks. – CBroe Aug 08 '23 at 08:00
  • What is the actual purpose of what you are doing there in the first place? – CBroe Aug 08 '23 at 08:02
  • 1
    I figured out the issue. Others faced similar issue and this answer solved it: https://stackoverflow.com/a/42334410/1634905 – sudoExclaimationExclaimation Aug 08 '23 at 08:13
  • 1
    Possible duplicate, per OP's comment: [ArrayBuffer to base64 encoded string](https://stackoverflow.com/questions/9267899/arraybuffer-to-base64-encoded-string) – halfer Aug 08 '23 at 10:23

0 Answers0