Introduction

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.
  1. <video controls width="500px" id="vid">
  2. <source src="vid.mp4" type="video/mp4" />
  3. </video>
This means I first need to upload the video to the 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 the client-side.
I came across something called as URL.createObjectURL().
It is a static method which creates DOMstring containing a Url representing the object.
Check the following code snippet.
  1. <div style="border:1px solid black">
  2. <h3>File Upload</h3>
  3. <input type="file" id="fl"></input>
  4. <br />
  5. <br />
  6. <input type="button" value="Validate" id="btn" />
  7. <br />
  8. <video controls width="500px" id="vid" style="display:none"></video>
  9. </div>
  10. <script type="text/ecmascript">
  11. var objectUrl;
  12. $(document).ready(function() {
  13. $("#fl").change(function(e) {
  14. var file = e.currentTarget.files[0];
  15. objectUrl = URL.createObjectURL(file);
  16. $("#vid").prop("src", objectUrl);
  17. });
  18. $('#btn').click(function() {
  19. var seconds = $("#vid")[0].duration;
  20. if (seconds <= 120)
  21. alert('Video duration should be more than 2 min');
  22. });
  23. });
  24. </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 the video element with blob object.
- On click of validating button, you can now easily access that video element and check its duration property (which is specified in seconds)
  1. if(seconds <= 120)
  2. alert('Video duration should be more than 2 min');
That’s it. I hope you will like this small blog stating the validation check for video duration on client side.