If you want that to be functional, consider the following approach:
- Begin by reading the file as an ArrayBuffer (this can later be sent directly to the server as a binary stream)
- Package it within a Blob object
- Create a URL for the blob object
- Set the URL as the video source
Once the video object triggers the loadedmetadata
event, you will be able to retrieve the duration.
Alternatively, you could utilize data-uri, although keep in mind that browsers might impose size restrictions and other limitations, especially crucial for video files. Additionally, there is a notable encoding/decoding overhead from the Base-64 process.
For instance...
Select a video file compatible with the browser (in practical scenarios, filter allowed file types based on video.canPlayType()
).
The duration will display once the aforementioned steps are completed (the example lacks error handling, so adjust accordingly).
var fileEl = document.querySelector("input");
fileEl.onchange = function(e) {
var file = e.target.files[0], // chosen file
mime = file.type, // save MIME type
rd = new FileReader(); // instantiate a FileReader
rd.onload = function(e) { // when file is read:
var blob = new Blob([e.target.result], {type: mime}), // create a blob of buffer
url = (URL || webkitURL).createObjectURL(blob), // generate o-URL for blob
video = document.createElement("video"); // initialize video element
video.preload = "metadata"; // preload setting
video.addEventListener("loadedmetadata", function() { // upon meeting data load requirements
document.querySelector("div")
.innerHTML ="Duration: "+ video.duration + "s"; // show duration
(URL || webkitURL).revokeObjectURL(url); // cleanup
// ... continue from here ...
});
video.src = url; // begin loading video
};
rd.readAsArrayBuffer(file); // read file object
};
<input type="file"><br><div></div>