1

I have given multiple upload file option but it is storing everything in one variable but i am not getting how to store seperate file encoded value in a seperate variable. It should create variable and store encoded value according to file upload.

<html>
<body>

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" multiple />
<div id="imgTest"></div>
<script type='text/javascript'>

    function encodeImageFileAsURL(index) {
        var filesSelected = document.getElementById("inputFileToLoad").files;
        index = index || 0;
        if (filesSelected.length > 0 && index < filesSelected.length) {
            var fileToLoad = filesSelected[index];

            var fileReader = new FileReader();

            fileReader.onloadend = function(fileLoadedEvent) {
                var srcData = fileLoadedEvent.target.result; // <--- data: base64

                var newImage = document.createElement('img');
                newImage.src = srcData;

                document.getElementById("imgTest").appendChild(newImage);
                if (index < filesSelected.length) {
                    encodeImageFileAsURL(index + 1)
                }
                console.log(srcData);    
            }
            fileReader.readAsDataURL(fileToLoad);
        }
    }
</script>
</body>
</html>

1 Answer 1

1

You may save the variable into an array, then access it whenever you want.

    var sourceArray = new Array(); // put this before the function delaction 


                fileReader.onloadend = function (fileLoadedEvent) {
                    var srcData = fileLoadedEvent.target.result; // <--- data: base64

                    sourceArray.push(srcData);

                    var newImage = document.createElement('img');
                    newImage.src = srcData;

                    document.getElementById("imgTest").appendChild(newImage);
                    if (index < filesSelected.length) {
                        encodeImageFileAsURL(index + 1)
                    }}

                    console.log(sourceArray);
Sign up to request clarification or add additional context in comments.

3 Comments

there is a missed } brackets , also add the array declaration outside the function , I tried and it works fines @user5397448
@user5397448 so you did not push the srcData into the array. sourceArray.push(srcData); it is so direct and simple .
Easy approach nice one

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.