user2212461 user2212461 - 5 months ago 31
Javascript Question

How can I set video source in html?

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?

Answer

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>