JS FileReader duplicating itself with previous values

I am quite new to JS promises and while working with them I got into a problem. First, let me explain what I am trying to achieve and what is getting achieved. I was creating a function that creates a file type input element that accepts images and then listens to onchange event handler on that element. When the user selects an image I call .then() method to resolve a promise which uses FileReader() to extract base64 of the image. What happens is that when I try to add the image again using that function the older image gets added as well. This repetition keeps on happening with the amount of older images already added. This is my code so far,

function handleImage(){
    const imageInput = document.createElement('input');
    imageInput.setAttribute('accept', 'image/*');
    imageInput.setAttribute('type', 'file');
    imageInput.id = "img-inp-tmp";
    imageInput.click();
    // Listen upload local image and save to server
    imageInput.onchange = () => {
        const imageFile = imageInput.files[0];
        if (/^image\//.test(imageFile.type)) 
        {
            getBase64(imageFile).then(
                data => insertImage(data)
            );                        
        } 
        else 
        {
            console.warn('You could only upload images.');
        }
    };
}

function getBase64(file) 
{
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

function insertImage(base64_string)
{
    // This function gets called multiple times based on how much handleImage() was called
}

The code above is basically is used to overwrite the default methods of the WYSIWYG HTML editor. So when I click on the add image button on the editor I call handleImage() function which then processes image upload. Now, this scenario is actually happening: When I add an image a the function works perfectly fine and gives me the base64 of that image which in turn I insert into the editor. But when I try to add image b First the function will give base64 of image a then it’ll give the base64 of image b. The function basically duplicates itself. And this problem keeps on duplicating when I add more images.

106 thoughts on “JS FileReader duplicating itself with previous values”

Leave a Comment