why this code returns undefined when I first run


I want to get a base64 string from an uploaded image. First time when i run the code, it returns undefined. When i run after it works fine. How can i fix this?

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Upload</title>
  </head>
  <body>
    <input type="file" id="file">
    <button id="button" onclick="upload()">Upload</button>
    <script type="text/javascript">
      var result;

      function getBase64(file) {
         var reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = function () {
           result = reader.result;
         };
         reader.onerror = function (error) {
           console.log('Error: ', error);
         };
         return result;
      }

      function upload() {
        var file = document.querySelector('input').files[0];
        console.log(getBase64(file));
      }
    </script>
  </body>
</html>

Source: JavaSript – Stack Overflow

November 18, 2021
Category : News
Tags: base64 | html | javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.