Javascript Image File Reader: readAsDataURL(image)

Published on Mar 5 2017

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.

File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.

The following example uses an input to browse and load an image from local machine.

javascript code example:

window.onload = function() 
{
    var fileInput = document.getElementById('fileInput');
    var output = document.getElementById('output');
    var buff = document.getElementById('buff');
            
    fileInput.addEventListener('change', function(e) 
    {
        var file = fileInput.files[0];
        var imageType = /image.*/;
        if (file.type.match(imageType)) 
        {
            var reader = new FileReader();
            reader.onload = function(e) 
            {
              output.innerHTML = "";
              var img = new Image();
              img.src = reader.result;
              output.appendChild(img);
              buff.innerHTML = reader.result;
            }
            reader.readAsDataURL(file);             
        }
    else 
        {
          output.innerHTML = "File not supported!";
        }
    });
}

HTML:

<div class="section-wrapper">
    <label for="">Select an image file: <input type="file" id="fileInput"></label>
</div>
<div id="output" class="section-wrapper"></div>
<div id="buff" class="section-wrapper"></div>

reference:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader