Show video preview using JavaScript

Sometimes we face a requirement to show a video preview to a user before uploading it to the server. Social media sites like Facebook and Twitter provide this type of functionality so users can see which video file is selected.

We can create similar functionality for showing video previews easily using JavaScript. In this article, we will take a simple example where the user can select a video file and we will show a preview of the selected file.

Video preview will reduce server load and same time user can check video file is valid or not. Here we will use the URL.createObjectURL() method to show a preview.

First of all, let’s define basic markup for our web page then we will add our JavaScript code for showing a preview. create a new file or you can use your existing markup for it.

<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8">
        <title>Video Preview Using JavaScript</title>
        <input id="video" type="file" name="file">

        <video width="320" height="240" controls>
            Your browser does not support the video tag.

Here, we just added a simple input field with the file type and assign id to it. Also defined HTML video element with height and width attributes.

Now we will add a trigger to show a preview. Whenever the event triggers, we set the video tag src as blobURL, which is the URL.createObjectURL of the selected video file. The browser will automatically show a preview of the video element and add basic control as per our attributes.

Further, we will add below JavaScript code at the end of the body tag.

document.getElementById("video").onchange = function(event) {
    let file =[0];

    let blobURL = URL.createObjectURL(file);

    document.querySelector("video").src = blobURL;

The above code will get the selected file and create a URL from the file. Then we will set the video tag’s src attribute with that URL which will show the video preview to the user.


In this article, we have taken a simple example showing a video preview to the user using JavaScript-based logic. There are many ready to use a library to perform this task easily. But those packages contain logic similar to this.