Display preview of the video the user selects by input

Asked

Viewed 61 times

1

In my application the user can select a video to add to the form, but before sending it I would like it to display the video when the user selects the file. I managed to do this already with images using Filereader in Javascript. With video does not work, I tried it but without result.

Just follow my code:

function exibirVideoPc() {
      document.getElementById("vid").onchange = function(event) {
        var file = event.target.file;
        var blobURL = URL.createObjectURL(file);
        document.querySelector("video").src = blobURL;
      }
}

THE HTML:

<div class="form-group">
   <input type="file" class="form-control-file" id="vid" name="vid" accept="video/*" onchange="exibirVideoPc();" required>
   <div class="invalid-feedback">Campo Obrigatório.</div>
</div>
<div id="embed-video" style="text-align:center;">
  <video width="480" controls>
     <source src="" id="video_here">
        Seu navegador não suporta vídeo HTML5.
   </video>
</div>

1 answer

1


Are you using onchange 2 times: one in the attribute calling the function and within the function creating a Event Handler onchange. You don’t need the function, just the Event hanlder that already captures the field change.

Now, you need to get the index [0] of the API files to play at src of source, but it is necessary to replace the tag video all.

Then if you want to run the video after it is loaded, use .play():

document.getElementById("vid").onchange = function() {
   var file = this.files[0];
   var blobURL = URL.createObjectURL(file);
   
   document.getElementById("embed-video").innerHTML = '<video width="480" controls>'
   +'<source src="'+ blobURL +'" id="video_here">'
   +'Seu navegador não suporta vídeo HTML5.</video>';
   
   document.querySelector("video").play();
}
<div class="form-group">
   <input type="file" class="form-control-file" id="vid" name="vid" accept="video/*" required>
   <div class="invalid-feedback">Campo Obrigatório.</div>
</div>
<div id="embed-video" style="text-align:center;">
  <video width="480" controls>
     <source src="" id="video_here">
        Seu navegador não suporta vídeo HTML5.
   </video>
</div>

  • Very good @Sam ! That’s right, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.