0

I want to select a file and after clicking a button, want to load the file into a video element, which should play immediately. Trying to input the file through type="text" works, but that would require me to type the link of the file. What I want is being able to select the file, like through explorer. type="file" allows me to select the file through explorer, but after that I cannot append the file into video.src because value property returns fakepath instead of the real path. Is there another way to do it?

<html>
<head>
    <title>Using File For Streaming</title>
</head>

<body>
<input type="file" id="videoUrl"/>
<button onClick="play()">Play Video</button>
<video id="videoPlayer" height="400" width="400" autoplay controls muted></video>
    <script>
        function play() {
            var videoUrl = document.getElementById('videoUrl').value;
            alert(videoUrl);
            var videoPlayer = document.getElementById('videoPlayer');
            videoPlayer.src = videoUrl;
            videoPlayer.load();
            videoPlayer.play();
        }
    </script>
</body>
</html>

1 Answers1

1

Use the URL.createObjectURL method, with your uploaded input.files[0] to feed your <source>'s src, then call the .load() method of your <video>.

inp.onchange = function(){
  source.src = URL.createObjectURL(inp.files[0]);
  vid.load();
  // even if it's just a pointer to the real file here
  vid.onended = function(){
      URL.revokeObjectURL(vid.currentSrc);
    };
  }
<video id="vid" controls>
  <source id="source"/>
</video>
<input id="inp" type="file" accept="video/*">
Kaiido
  • 87,051
  • 7
  • 143
  • 194