0

I'm a compete newbe and I just spent 4 hours trying to solve my questions by reading through many many threads.

In the end, maybe someone can help me and rewrite the code so that I can return the value of the variable srcData from within the following code.

function encodeImageFileAsURL() 
  {
    filesSelected = document.getElementById("inputFileToLoad").files;
  if (filesSelected.length > 0) 
    {
    fileToLoad = filesSelected[0];
    fileReader = new FileReader();
        fileReader.onload = function(fileLoadedEvent)
    
        {
        srcData = fileLoadedEvent.target.result;
        newImage = document.createElement('img');
        newImage.src = srcData;
        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
        console.log(srcData);
        } 
        fileReader.readAsDataURL(fileToLoad);
        }  
  }

Thank so much for your help.

Hope I will be able to run

console.log(srcData);

after running the function and use that value further.

Many thanks

tried setting global var, localstorage, etc but everytime I got it wrong

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • `fileReader.onload` executes once the data has been read. Put your code that needs to operate on the data inside there. You may not return srcData from `encodeImageFileAsURL` because it has not yet been read at the time that `encodeImageFileAsURL` terminates. – James Apr 10 '23 at 20:24

0 Answers0