67

In one of my module, I need to browse video from input[type='file'], after that I need to show selected video before starting upload.

I am using basic HTML tag to show. but it is not working.

Here is code:

$(document).on("change",".file_multi_video",function(evt){
  
  var this_ = $(this).parent();
  var dataid = $(this).attr('data-id');
  var files = !!this.files ? this.files : [];
  if (!files.length || !window.FileReader) return; 
  
  if (/^video/.test( files[0].type)){ // only video file
    var reader = new FileReader(); // instance of the FileReader
    reader.readAsDataURL(files[0]); // read the local file
    reader.onloadend = function(){ // set video data as background of div
          
          var video = document.getElementById('video_here');
          video.src = this.result;
      }
   }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<video width="400" controls >
              <source src="mov_bbb.mp4" id="video_here">
            Your browser does not support HTML5 video.
          </video>


 <input type="file" name="file[]" class="file_multi_video" accept="video/*">
Ronak Patel
  • 3,324
  • 4
  • 21
  • 31

7 Answers7

101

@FabianQuiroga is right that you should better use createObjectURL than a FileReader in this case, but your problem has more to do with the fact that you set the src of a <source> element, so you need to call videoElement.load().

$(document).on("change", ".file_multi_video", function(evt) {
  var $source = $('#video_here');
  $source[0].src = URL.createObjectURL(this.files[0]);
  $source.parent()[0].load();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<video width="400" controls>
  <source src="mov_bbb.mp4" id="video_here">
    Your browser does not support HTML5 video.
</video>

<input type="file" name="file[]" class="file_multi_video" accept="video/*">

Ps: don't forget to call URL.revokeObjectURL($source[0].src) when you don't need it anymore.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • 1
    Should be the accepted answer! By the way, what´s the impact of not doing URL.revokeObjectURL($source[0].src) at any point ? – Carlos Med Nov 04 '17 at 15:28
  • 1
    @CarlosArturoFyuler in this exact case (a user provided File through `input[type=file]`, not so much... The blobURI returned by `createObjectURL` here just holds a direct symlink to the file on the user's disk, so the memory impact is less than important. But in other cases, it does have real consequences: an unrevoked blobURI from a generated or fetched Blob will hold its data in memory until the session ends. And even worse, with MediaStream, like gUM (at the time this answer was written cOU was still the way to display MediaStreams, now deprecated), it may block the device (e.g web-cam). – Kaiido Nov 05 '17 at 12:52
  • Thank's for the clarification :) – Carlos Med Nov 09 '17 at 22:58
  • 1
    $source.parent(...)[0].load is not a function – Fernando Torres Jun 13 '20 at 02:29
  • @Kaiido i'm sorry i don't know much about `URL.revokeObjectURL($source[0].src)` so could you tell me in the above code where exactly should i call `URL.revokeObjectURL($source[0].src)`? – Amit kumar Jan 15 '22 at 07:01
  • @Amitkumar when you don't need the blob URI anymore, so generally once the resource has been fetched, here when the ` – Kaiido Jan 15 '22 at 12:12
  • how do I disable the option on the player that lets any people download the video file? – minjunkim7767 Feb 03 '22 at 14:32
13

Do not forget that it uses jquery library

Javascript

$ ("#video_p").change(function () {
   var fileInput = document.getElementById('video_p');
   var fileUrl = window.URL.createObjectURL(fileInput.files[0]);
   $(".video").attr("src", fileUrl);
});

Html

< video controls class="video" >
< /video >
Fabian Quiroga
  • 131
  • 1
  • 4
6

Here is an easy peasy solution

document.getElementById("videoUpload").onchange = function(event) {
  let file = event.target.files[0];
  let blobURL = URL.createObjectURL(file);
  document.querySelector("video").style.display = 'block';
  document.querySelector("video").src = blobURL;
}
<input type='file'  id='videoUpload'/>

<video width="320" height="240" style="display:none" controls autoplay>
  Your browser does not support the video tag.
</video>

the solution is using vanilla js so you don't need JQuery with it, tested and works on chrome, Goodluck

Abdulbasit
  • 534
  • 8
  • 13
3

If you are facing this issue. Then you can use the below method to resolve the above issue.

Here is the html code:

//input tag to upload file
<input class="upload-video-file" type='file' name="file"/>

//div for video's preview
 <div style="display: none;" class='video-prev' class="pull-right">
       <video height="200" width="300" class="video-preview" controls="controls"/>
 </div>

Here is the JS function below:

$(function() {
    $('.upload-video-file').on('change', function(){
      if (isVideo($(this).val())){
        $('.video-preview').attr('src', URL.createObjectURL(this.files[0]));
        $('.video-prev').show();
      }
      else
      {
        $('.upload-video-file').val('');
        $('.video-prev').hide();
        alert("Only video files are allowed to upload.")
      }
    });
});

// If user tries to upload videos other than these extension , it will throw error.
function isVideo(filename) {
    var ext = getExtension(filename);
    switch (ext.toLowerCase()) {
    case 'm4v':
    case 'avi':
    case 'mp4':
    case 'mov':
    case 'mpg':
    case 'mpeg':
        // etc
        return true;
    }
    return false;
}

function getExtension(filename) {
    var parts = filename.split('.');
    return parts[parts.length - 1];
}
Owen M
  • 2,585
  • 3
  • 17
  • 38
Pragya Sriharsh
  • 529
  • 3
  • 6
2

Lets make it easy

HTML:

<video width="100%" controls class="myvideo" style="height:100%">
<source src="mov_bbb.mp4" id="video_here">
Your browser does not support HTML5 video.
</video>

JS:

function readVideo(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();   
        reader.onload = function(e) {
            $('.myvideo').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
}

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Usama Shahid
  • 769
  • 6
  • 9
0

Preview an video before uploading using by jQuery

$(function(){
    $('#videoFileInput').on('change',function(){
        var file = this.files[0];
        var reader = new FileReader();
        reader.onload = viewer.load;
        reader.readAsDataURL(file);
    });
    var viewer = {
        load : function(e) {
            $('#preview').show();
            $('#preview').attr('src',e.target.result);
        },
    }
});
<input type="file" name="video_file" class="form-control" accept="video/mp4" id="videoFileInput">

<video id="preview" width="600" controls style="display: none;margin-top: 25px;">
  Your browser does not support HTML5 video.
</video>
InSync
  • 4,851
  • 4
  • 8
  • 30
-1

This is example on VUE JS: preview PICTURE

Example SOURCE CODE - DRAG-DROP _part

Example with RENDERing & createObjectURL() using VIDEO.js

p.s. i just want to improve "Pragya Sriharsh" solution:

const = isVideo = filename =>'m4v,avi,mpg,mov,mpg,mpeg'
.split(',')
.includes( getExtension(filename).toLowerCase() )

And .. please don't use JQuery, it's now 2k19:-);

-> So:

const getExtension = filename => {
    const parts = filename.split('.');
    return parts[parts.length - 1];
}

... And let the rest of the work will be done by Webpack 4!

  • jQuery is still being used by many major web platforms and coding a whole VUE or React component just to display a video isnt feasible. jQuery is still relevant and supported. – Drmzindec May 14 '21 at 12:12
  • 1
    Jquery is supported just like my nokia 3310 can still make calls on my network. That doesn't mean you shouldn't try and move forward with the times. JQuery is trash. – AhrenFullStop Oct 29 '21 at 07:35