Get video duration after uploading

After uploading a file, Uploadcare Widget allows you to get file information provided by the Upload API. The fileinfo object contains various fields such as file name, size, type, image information, etc. However, if the file is a video, its fileinfo object won’t contain its duration and other video-specific information.

Sometimes, it’s crucial to have the duration of the media file once it has been uploaded. For example, if your app requires videos not to be longer than N seconds, and to ensure this, it trims too long videos with our Video processing API.

In this case, video duration can be obtained with some JavaScript. To do so, you need to get the file object, create an object URL out of it, create a hidden HTML video element, and set its src to the object URL generated. After that, the video length will be available through the duration property of the video element.

// get the widget object
const widget = uploadcare.Widget('[role=uploadcare-uploader]');
// regexp to check if the file is audio/video
const regexp = /^(audio|video)\//gi;
// wait until a file is uploaded and get it's info
widget.onUploadComplete(fileInfo => {
  if (regexp.test(fileInfo.mimeType)) {
    // get the file object
    const fileObject = fileInfo.sourceInfo.file;
    // create a URL from the file object
    const url = URL.createObjectURL(fileObject);
    // create a hidden video element 
    const video = document.createElement('video');
    // set the file object URL as the src of the video element
    video.src = url;
    // get video/audio duration when it's available
    video.addEventListener('loadedmetadata', () => {
      console.log(`Duration: ${video.duration.toFixed(2)}s`);
  // any additional post-uploading logic can go here

This technique works for audio files as well. You can play around with a live demo here.

Hello Alex,

Thank you so much for the code but the regular expression seems to be like not accurate and getting the duration only works with local files.I made some changes on the code. so I’m just gonna leave it here someone might use it.

var regexp = /(audio|video)\/(.*)/gm; 

widget.onUploadComplete(function(fileInfo) {

var regularexp = regexp.test(fileInfo.mimeType); 

  var url = fileInfo.cdnUrl; // Get the video/audio URL from uploadcare response.
  var video = document.createElement('video');
  video.src = url;
  video.addEventListener('loadedmetadata', function() {
    var video_duration = video.duration.toFixed(2);


1 Like

@splasheo Perfect! Thank you for sharing this. Please, note that if you set a CDN URL as the src of the video element, the browser will load the file from the CDN, hence generate CDN traffic that will be reflected in your usage stats.