2

this code always return me '3' in alert.

I select two files together (ones .mp4 format and second ones .zip format)

    function readFile(input) {
        var counter = input.files.length;
        for(x = 0; x<counter; x++){
            if (input.files && input.files[x]) {
                var extension = input.files[x].name.split('.').pop().toLowerCase();
                var reader = new FileReader();

                reader.onload = function (e) {
                    urlss = 1;
                    if(extension == 'mp4'){
                        urlss = 2;
                    }else{
                        urlss = 3;
                    }
                    alert(urlss);
                };
                reader.readAsDataURL(input.files[x]);
            }
        }
    }
<input type="file" id="files" name="files[]" accept=".png, .jpg, .jpeg, .zip, .mp4" onchange="readFile(this);" multiple />

9
  • 3
    I assume urlss = '"2.jpg"; is a typo in the question? Commented Aug 24, 2019 at 14:26
  • You can return array Commented Aug 24, 2019 at 14:26
  • can you please add the full relevant code.... Commented Aug 24, 2019 at 14:31
  • @AbhisarTripathi this is full code. it read files form an input file. Commented Aug 24, 2019 at 14:43
  • @icecub that was a misspelling. Commented Aug 24, 2019 at 14:45

1 Answer 1

2

That is because of var hoisting

The onload function calling after the for was ended and extension == last file extension

Try replace var with const:

function readFile(input) {
    var counter = input.files.length;
    for(let x = 0; x < counter; x++){
        if (input.files && input.files[x]) {
            const extension = input.files[x].name.split('.').pop().toLowerCase();
            const reader = new FileReader();

            reader.onload = function (e) {
                urlss = 1;
                if(extension == 'mp4'){
                    urlss = 2;
                }else{
                    urlss = 3;
                }
                alert(urlss);
            };
            reader.readAsDataURL(input.files[x]);
        }
    }
}

Update

Please check the Webber's comment below.

Sign up to request clarification or add additional context in comments.

1 Comment

So the real problem actually was that the reader.onload gets overridden in every iteration. It would be better if you define 1 FileReader, that has one onload function, and run readAsDataURl once per iteration on that single file reader. This answer creates a separate file reader for every file that is read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.