How to display and image that hasn’t been uploaded with vanilla javascript

Sometimes it’s nice to display an image, as a preview before it’s uploaded, or you might want to display an image for some other reason.

For this purpose we use URL.createObjectURL.

<html lang="eng">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>
<body>
  <main>
    <input type="file"  accept="image/*" name="image" id="file"  onchange="loadFile(event)" style="display: none;">
    <label for="file" style="cursor: pointer;">Click to preview image</label>

    <img id="image" width="200">
  </main>
  </html>

  <script>

  var loadFile = function(event) {
    var image = document.getElementById('image');
    image.src = URL.createObjectURL(event.target.files[0]);
  };

/* The browser will automatically clean up memory 
but the following line should be added if the 
object isn't needed any more*/

URL.revokeObjectURL(this.src);

</script>

TIP: to actually see the blob file, type “chrome://blob-internals/” in the browser window.

By using “URL.revokeObjectURL(image.src);” in the above code, you will see the blob disappear after 10 seconds or so if you refresh the browser. It doesn’t disappear as soon as “URL.revokeObjectURL(image.src);” is executed.

Leave a Reply