Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set a video length limit on a HTML5 file upload?

When uploading a video through a HTML5 input such as:

<input type="file" id="input">

I know it is possible to set a limit on the file size using PHP / Node.Js.

Is there a way to set a limit on the video length, not the file size?

I.E: Only allow a user to upload videos which are 15 seconds or less.

like image 901
Connor Gutman Avatar asked Dec 05 '25 05:12

Connor Gutman


1 Answers

Here's what I found:

Solution 1: Create a video element that plays a local video file and then runs video.duration on it.

var vid = document.getElementById("myVideo");

function myFunction() { 
    alert(vid.duration);
} 

(function localFileVideoPlayer() {
	'use strict'
  var URL = window.URL || window.webkitURL
  var displayMessage = function (message, isError) {
    var element = document.querySelector('#message')
    element.innerHTML = message
    element.className = isError ? 'error' : 'info'
  }
  var playSelectedFile = function (event) {
    var file = this.files[0]
    var type = file.type
    var videoNode = document.querySelector('video')
    var canPlay = videoNode.canPlayType(type)
    if (canPlay === '') canPlay = 'no'
    var message = 'Can play type "' + type + '": ' + canPlay
    var isError = canPlay === 'no'
    displayMessage(message, isError)

    if (isError) {
      return
    }

    var fileURL = URL.createObjectURL(file)
    videoNode.src = fileURL
  }
  var inputNode = document.querySelector('input')
  inputNode.addEventListener('change', playSelectedFile, false)
})()
<h3>Step 1: Upload a video</h3>
<h3>Step 2: Get length</h3>
<h3>Step 3: ???</h3>
<h3>Step 4: Profit</h3>
<button onclick="myFunction()" type="button">Get video length</button>
<hr>
<div id="message"></div>
<input type="file" accept="video/*"/>
<video controls autoplay id="myVideo"></video>

Solution 2: use mediainfo.js https://mediainfo.js.org/

like image 83
Connor Gutman Avatar answered Dec 07 '25 17:12

Connor Gutman