Recipe 10.2

Loading an Image as a Data URL

Select an image file to load into the browser.

Demo

Code

JavaScript
const fileInput = document.querySelector('#file-upload');
const content = document.querySelector('#file-content');

fileInput.addEventListener('change', event => {
  const [file] = fileInput.files;
  const reader = new FileReader();

  reader.addEventListener('load', event => {
    content.src = event.target.result;
  });

  reader.addEventListener('error', event => {
    console.log('error', event);
  });

  reader.readAsDataURL(file);
});
HTML
<label for="file-upload" class="form-label">Image</label>
<input
  id="file-upload"
  type="file"
  accept="image/*"
  class="form-control"
>

<div class="my-4">
  <label class="form-label">Preview</label>
  <div class="card">
    <div class="card-body">
      <img id="file-content">
    </div>
  </div>
</div>
Web API Cookbook
Joe Attardi