Upload and preview a video using vanilla JavaScript

tepexic

Jesús Velázquez

Posted on November 11, 2020

Upload and preview a video using vanilla JavaScript

I recently googled the title, and found several solutions on how to do it with jQuery, but I was working with Vue and needed a pure JS implementation. Here's a codepen with the code.

We need an input field and a video tag in our HTML to begin with, like this:

<input type="file" accept="video/*" id="input-tag"/>
<hr>
<video controls id="video-tag">
  <source id="video-source" src="splashVideo">
  Your browser does not support the video tag.
</video>
Enter fullscreen mode Exit fullscreen mode

Now, in the JS, let's get the handles of our HTML elements

const videoSrc = document.querySelector("#video-source");
const videoTag = document.querySelector("#video-tag");
const inputTag = document.querySelector("#input-tag");
Enter fullscreen mode Exit fullscreen mode

With this ready, we can write the function that will read the video and show it inside the video tag, we're using the FileReader API:

function readVideo(event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.onload = function(e) {
      videoSrc.src = e.target.result
      videoTag.load()
    }.bind(this)

    reader.readAsDataURL(event.target.files[0]);
  }
}
Enter fullscreen mode Exit fullscreen mode

The trick here consists on reading the selected file as URL. This way, it can be read by the video tag.

When the file has been uploaded (.onload event), we simply point the src property of the video to the result of the FileReader instance. Then execute the load() method from the video tag.

That's it. I hope it was helpful. Here's a codepen with the code again.

Header image by Kushagra Kevat

💖 💪 🙅 🚩
tepexic
Jesús Velázquez

Posted on November 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related