DEV Community

Cover image for Upload and preview a video using vanilla JavaScript
Jesús Velázquez
Jesús Velázquez

Posted on • Updated on

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

Top comments (3)

Collapse
 
abrahambrookes profile image
Abraham Brookes

Thanks for this! really helped me out, although I got a console error saying that source.load() is not a function. I removed that line and it still worked on firefox, edge and chrome.

Collapse
 
doolpool profile image
DoolPool

Thanks for this! really helped me out.

Collapse
 
bkmillanzi profile image
Bkmillanzi

Okay, so... Any ideas on how to trim a video's length!? not just the quality... if at all