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>
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");
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]);
}
}
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)
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.Thanks for this! really helped me out.
Okay, so... Any ideas on how to trim a video's length!? not just the quality... if at all