Upload Video in chunks with preview and progress bar
Upload Video in chunks with preview and progress bar
by AndrewBuntsev
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="uploadVideoFile" accept="video/*" />
<div id="videoSourceWrapper">
<video style="width: 100%;" controls>
<source id="videoSource"/>
</video>
<div id="uploadVideoProgressBar" style="height: 5px; width: 1%; background: #2781e9; margin-top: -5px;"></div>
</div>
JavaScript
$(document).ready(function(){
$("#videoSourceWrapper").hide();
});
$('#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();
UploadVideo(fileInput.files[0]);
}
} else {
console.log('No found "files" property');
}
}
);
function UploadVideo(file) {
var loaded = 0;
var chunkSize = 500000;
var total = file.size;
var reader = new FileReader();
var slice = file.slice(0, chunkSize);
// Reading a chunk to invoke the 'onload' event
reader.readAsBinaryString(slice);
console.log('Started uploading file "' + file.name + '"');
$('#uploadVideoProgressBar').show();
reader.onload = function (e) {
//Just simulate API
setTimeout(function(){
loaded += chunkSize;
var percentLoaded = Math.min((loaded / total) * 100, 100);
console.log('Uploaded ' + Math.floor(percentLoaded) + '% of file "' + file.name + '"');
$('#uploadVideoProgressBar').width(percentLoaded + "%");
//Read the next chunk and call 'onload' event again
if (loaded <= total) {
slice = file.slice(loaded, loaded + chunkSize);
reader.readAsBinaryString(slice);
} else {
loaded = total;
console.log('File "' + file.name + '" uploaded successfully!');
$('#uploadVideoProgressBar').hide();
}
}, 250);
}
}
function PostChunk(){
//Send the sliced chunk to the REST API
$.ajax({
...