Sometimes we face a requirement to show a video preview to user before uploading it to the server. Social media sites like Facebook and Twitter provides this type of functionality so user 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 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 URL.createObjectURL() method to show 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.
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 preview. Whenever the event triggers, we set the video tag src as blobURL, which is URL.createObjectURL of the selected video file. The browser will automatically show a preview of video element and add basic control as per our attributes.
Further, we will add below JavaScript code at end of the body tag.
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.
Conclusion
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.