2

I need a way to let users select a local video file as source for my html video element.

Setting the source doesn't seem to work because I can't access the full path from a standard javascript file dialog.

I tried the following:

//THE VIDEO ELEMENT
<video id="video1" muted>
     <source src="" type="video/mp4" />
</video>

//THE DIALOG BUTTON TO SET VIDEO SOURCE
<input type='file' onchange="readURL(this);" />

<script>
  var video = document.getElementById("video1");

  function readURL(input) {
    //THE METHOD THAT SHOULD SET THE VIDEO SOURCE
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        video.src = input.files[0]
      };
    }
  }
</script>

How can I create a button that allows to select and upload local video files into the HTML5 video element?

user2212461
  • 3,105
  • 8
  • 49
  • 87
  • 1
    Possible duplicate of [Play local (hard-drive) video file with HTML5 video tag?](http://stackoverflow.com/questions/8885701/play-local-hard-drive-video-file-with-html5-video-tag) – michaPau Apr 25 '16 at 19:33

2 Answers2

2

I made some changes and work's fine! I tested in Chrome and Firefox.

//THE VIDEO ELEMENT
<video id="video1" muted>
    <source src="" type="video/mp4" />
</video>

//THE DIALOG BUTTON TO SET VIDEO SOURCE
<input id="file" type='file' onchange="readURL(this);" />

<script>
    var video = document.getElementById("video1");

    function readURL(input) {
        //THE METHOD THAT SHOULD SET THE VIDEO SOURCE
        if (input.files && input.files[0]) {
            var file = input.files[0];
            var url = URL.createObjectURL(file);
            console.log(url);
            var reader = new FileReader();
            reader.onload = function() {
                video.src = url;
                video.play();
            }
            reader.readAsDataURL(file);
        }
    }
</script>
0

For myself I solved it in separated js and html files like this: html:<input id="file" type='file'/>

javascript:

document.getElementById('file').onchange = function(){
        console.log('test');
        readURL(this);
    }

function readURL(input) {
    //THE METHOD THAT SHOULD SET THE VIDEO SOURCE
    if (input.files && input.files[0]) {
        var file = input.files[0];
        var url = URL.createObjectURL(file);
        console.log(url);
        var video = document.getElementById("video1");
        var reader = new FileReader();
        reader.onload = function() {
            video.src = url;
            video.play();
        }
        reader.readAsDataURL(file);
    }
}
leocod
  • 1
  • 1