Tuesday, March 12, 2019

Upload Video in chunks with preview and progress bar using JavaScript

So, we have 3 following goals here:
  1. Preview video before it is uploaded
  2. Upload video file in small chunks
  3. Display a progress bar
All these tasks are achievable with JS and jQuery without any other libraries.
For choosing a video file we will use the standard input element
<input type="file" id="uploadVideoFile" accept="video/*" />
So to access the chosen file we will call
var fileInput = document.getElementById("uploadVideoFile");
To display video we need a video element
div id="videoSourceWrapper">
   <video style="width: 100%;" controls>
      <source id="videoSource"/>
   </video>
</div>
The following snippet displays the video after it is chosen in the video element for preview
$('#uploadVideoFile').on('change',
    function() {
        var fileInput = document.getElementById("uploadVideoFile");
        console.log('Trying to upload the video file: %O', fileInput);

        if ('files' in fileInput) {
            if (fileInput.files.length === 0) {
                alert("Select a file to upload");
            } else {
                var $source = $('#videoSource');
                $source[0].src = URL.createObjectURL(this.files[0]);
                $source.parent()[0].load();
                $("#videoSourceWrapper").show();
            }
        } else {
            console.log('No found "files" property');
        }
    }
);


As you can see, you can watch any video file having all necessary controls in the video player. Now let's have a look how to upload the video on your server.