I had a requirement where I had a file upload control with me and I wanted to validate the video duration before uploading it. I did lot of R & D to find a way of validating the video duration to be let say greater than 2minutes before being uploaded.
HTML UI
We know, in HTML 5 we can check the duration of video using video element but the problem is video element needs to set with the source.
- <video controls width="500px" id="vid">
- <source src="vid.mp4" type="video/mp4" />
- </video>
This means I first need to upload the video to server to set the src attribute, but that will add overhead to the server when the validation of 2minutes doesn’t match. So I need a way that will work on client side.
I came across something called as URL.createObjectURL().
It is a static method which create DOMstring containing a Url representing the object.
Check the following code snippet.
- <div style="border:1px solid black">
- <h3>File Upload</h3>
- <input type="file" id="fl"></input>
- <br/>
- <br/>
- <input type="button" value="Validate" id="btn"/>
- <br />
- <video controls width="500px" id="vid" style="display:none"></video>
- </div>
- <script type="text/ecmascript">
- var objectUrl;
-
- $(document).ready(function(){
- $("#fl").change(function(e){
- var file = e.currentTarget.files[0];
- objectUrl = URL.createObjectURL(file);
- $("#vid").prop("src", objectUrl);
- });
-
- $('#btn').click(function(){
- var seconds = $("#vid")[0].duration;
- if(seconds <= 120)
- alert('Video duration should be more than 2 min');
- });
-
- });
-
-
- </script>
Explanation:
- On fileupload file selection, get the video file and create an ObjectUrl of that file.
- Add a video element on the page but keep it hidden.
- Set the src attribute of video element with blob object.
- On click of validate button, you can now easily access that video element and check its duration property (which is specifically in seconds)
- if(seconds <= 120)
- alert('Video duration should be more than 2 min');
That’s it. Hope you will like this small blog stating the validation check for video duration on client side.