JS: How to take new image value from input

I’m trying to get an image from input convert it to array as well to display the new image into the imgPicture.src. However, I’m either getting undefined or empty source. Any possible solution? Thank you in advance.

    let changePicInput = document.createElement("input");
    changePicInput.type = "file";
    changePicInput.id = `file-${finalArray[i].Id}`;
    changePicInput.style.display = "none";
    changePicInput.addEventListener("change", function () {

        let arrBinaryFile = [];
        let file = document.getElementById(`file-${materialId}`).files[0];
        let reader = new FileReader();

        // Array
        reader.readAsArrayBuffer(file);
        reader.onloadend = function (evt) {

            if (evt.target.readyState == FileReader.DONE) {
                var arrayBuffer = evt.target.result,
                    array = new Uint8Array(arrayBuffer);
                for (var i = 0; i < array.length; i++) {
                    arrBinaryFile.push(array[i]);
                }
            }
        }

        // Display the image rightaway
        imgPicture.src = file.value;
    });

>Solution :

Hope it helps!

    let imgPicture = document.querySelector('#imgPicture');  // Added the line.
    
    let changePicInput = document.createElement("input");
    changePicInput.type = "file";
    changePicInput.id = `file-565656`; // Changed the line.
    changePicInput.style.display = "block";  // Changed the line.
    document.body.appendChild(changePicInput);  // Added the line.
    changePicInput.addEventListener("change", function () {
    
        let arrBinaryFile = [];
        let file = document.getElementById(`file-565656`).files[0];  // Changed the line.
        let reader = new FileReader();

        // Array
        reader.readAsArrayBuffer(file);
        reader.onloadend = function (evt) {

            if (evt.target.readyState == FileReader.DONE) {
                var arrayBuffer = evt.target.result,
                    array = new Uint8Array(arrayBuffer);
                for (var i = 0; i < array.length; i++) {
                    arrBinaryFile.push(array[i]);
                }
            }
        }

        // Display the image rightaway
        //imgPicture.src = file.value;
        imgPicture.src = URL.createObjectURL(file)  // Added the line.
        console.log(file);  // Added the line.
    });
<body>
<img id="imgPicture">
</body>

Leave a Reply