1

Let's have the following page:

<html>
<head><meta charset="utf-8"></head>
<body>

<div><input type="file" id="file0" onchange="readFile(event)" /></div>
<div><input type="file" id="file1" onchange="readFile(event)" /></div>
<input type="button" value="send" onclick="sendFile()" />

<script>

var glob = new Array();

function readFile(event) {
    var input = event.target;
    glob.push(input.files[0]);
    console.log(glob);
}

function sendFile() {
    var i;

    for (i = 0 ; i < glob.length ; i++) {
        console.log(glob[i].name);
        var reader = new FileReader();
        reader.onload = function(){
            var arr = reader.result;
            var uint8View = new Uint8Array(arr);      
            console.log(uint8View);
        };
        reader.readAsArrayBuffer(glob[i]);
    }
}

</script>
</body>
</html>

I'm loading 2 files from my computer and click on "send". But I'm receiviving error message on console in FF: TypeError: invalid arguments. Different error message in IE: Typed array constructor argument is invalid. Seems to me that problem is with Uint8Array() but what's wrong? If I send a single file it is okay.

user3719454
  • 994
  • 1
  • 9
  • 24
  • What is `arr`? What does it actually contain? I presume its a string. –  Apr 28 '17 at 13:14
  • @Amy: See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/result). For a successful call to `readAsArrayBuffer`, it's an `ArrayBuffer`. – T.J. Crowder Apr 28 '17 at 13:18
  • @T.J.Crowder oh! that's part of JS! I was under the impression it was some custom class. nevermind then –  Apr 28 '17 at 13:20
  • 1
    `reader` no longer refers to the reader as of when `onload` fires, because you've updated the variable with a new value. So you're accessing `result` on the **last** `FileReader`, which probably isn't complete yet. This is the classic closure-in-loops problem. You could just use `this` instead of `reader` in the callback, or use the various solutions in the linked question's answers. – T.J. Crowder Apr 28 '17 at 13:21
  • @Amy: Well, not JavaScript, but the File API which is implemented in modern browsers, yes. :-) (`ArrayBuffer` is built into JavaScript, though, if that's what you meant.) – T.J. Crowder Apr 28 '17 at 13:24
  • 1
    @T.J. Crowder I was struggling with this for hours..... it is working with `this`... thanks :D – user3719454 Apr 28 '17 at 13:30

0 Answers0