1

I am trying to dynamically add a video file for play.

<html>
    <head> <title></title>
        <script src='./jquery/jquery-1.11.2.min.js'></script>
    </head>
    <body>
        <input type='file' accept='video/*' id='videofile' />
        <video controls id='match'> 

        </video>

        <button id='fire'>Click me</button>

        <script type="text/javascript">
            $(document).ready(function() {
                $('#fire').click(function(event){
                    //alert($('#videofile')[0].files[0].name);
                    $('#match').append("<source src='" + $('#videofile')[0].files[0].name + "' type='video/mp4'>" );
                });
            });
        </script>
    </body>
</html>

But I am not sure of the correct procedure, since I have only the file-name but not the complete path. How could I achieve this?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328
  • Depending on the size of the video, you may find the answer I gave in the following to be of assistance. http://stackoverflow.com/questions/28619550/javascript-play-uploaded-audio/28621015#28621015 I have tested this approach with videos of up to 13.3 Mb in size. :) – enhzflep Mar 01 '15 at 12:45
  • @enhzflep I want to play without upload,directly from hard-disk – Suhail Gupta Mar 01 '15 at 12:47
  • yes, I realize this. Try the solution I posted - it doesn't require a server, nor any upload - it works entirely client-side. – enhzflep Mar 01 '15 at 12:49

1 Answers1

3

Check this article: Reading files in JavaScript using the File APIs.

Try this:

HTML

<input type="file" accept='video/*' onchange="playVideo(this)" />
<video id="match" controls></video>

JS

function playVideo(obj) {
  var myvideo = document.getElementById('match');
  var reader = new FileReader();
  reader.onload = (function(video) {
     return function(e) {
       video.src = e.target.result;
     };
  })(myvideo);
  reader.addEventListener('load', function() {
    myvideo.play()
  });
  reader.readAsDataURL(obj.files[0]);
}

See an Example.

I tested it with sample videos from Wikimedia commons in Chrome. Download these files and test it yourself:

cch
  • 3,336
  • 8
  • 33
  • 61