user5397448 user5397448 - 3 months ago 11
HTML Question

value not getting stored in a variable

I have created a form where it asks user to upload his/her photo. But i am not able to save encoded value of my image. I want to save this value in a variable. I am not getting why my value is not getting saved in 'result' variable.

<html>
<body>
<input type="file" id="inp"/>
<img id="img" />
<div id="b64"></div>

<script type="text/javascript">
function EL(id) { return document.getElementById(id); }

function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.onload = function(e) {
EL("img").src = e.target.result;
EL("b64").innerHTML = e.target.result;
};
var result = FR.readAsDataURL( this.files[0] );
console.log(result);
}
}

EL("inp").addEventListener("change", readFile, false);

</script>
</body>
</html>

Answer

Because event onload runs asynchronously, and you try to access the value synchronously, which result to undefined

move your logic inside onload, or if you want synchronous code style use promises instead.

<html>
<body>
<input type="file" id="inp"/>
<img id="img" />
<div id="b64"></div>

<script type="text/javascript">
function EL(id) { return document.getElementById(id); } 

function readFile() {
  if (this.files && this.files[0]) {
    var FR= new FileReader();
    FR.onload = function(e) {
      EL("img").src       = e.target.result;
      EL("b64").innerHTML = e.target.result;

      //put your code here
      console.log(e.target.result);

    };       
    FR.readAsDataURL( this.files[0] );
  }
}

EL("inp").addEventListener("change", readFile, false);

</script>
</body>
</html>