• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Help with Upload functionality

chrisj

Coder
I am testing this code, where a video is recorded, start, stopped & replayed successfully. However, I don't have the upload part correct. Nothing happens upon selecting the upload button. Here's the code:

HTML:
<div class="nowrap">
 <button id="btn-start-recording">Start <br/>Recording</button>
 <button id="btn-stop-recording" disabled>Stop <br/>Recording</button>
 <button class="upload" disabled>Upload <br/>Recording</button>
 <button id="reset" onclick="resetCamera()">Reset <br/>Camera</button>
</div>
    <hr>
    <video controls autoplay playsinline></video>
    var video = document.querySelector('video');

JavaScript:
function captureCamera(callback) {
        navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(function(camera) {
            callback(camera);
        }).catch(function(error) {
            alert('Unable to capture your camera. Please check console logs.');
            console.error(error);
        });
    }

    function stopRecordingCallback() {
        video.src = video.srcObject = null;
        video.muted = false;
        video.volume = 1;
        video.src = URL.createObjectURL(recorder.getBlob());

        recorder.camera.stop();
        recorder.destroy();
        recorder = null;
    }

    var recorder; // globally accessible

    document.getElementById('btn-start-recording').onclick = function() {
        this.disabled = true;
        captureCamera(function(camera) {
            video.muted = true;
            video.volume = 0;
            video.srcObject = camera;

            recorder = RecordRTC(camera, {
                type: 'video'
            });

            recorder.startRecording();

            // release camera on stopRecording
            recorder.camera = camera;

            document.getElementById('btn-stop-recording').disabled = false;
        });
    };

    document.getElementById('btn-stop-recording').onclick = function() {
        this.disabled = true;
        recorder.stopRecording(stopRecordingCallback);
    };

               ///////////////////////////////////////////////////
                        //Reset the Camera
                                   function resetCamera(){
                                      location.reload();
                                    }
            //////////////////////////////////////////

                          //   uploading functionality

                    var blob, fileName, fileObject;
                  function uploadBlob(blob) {
                      prepareBlob(blob);
                            InitUploading();
                  }
                //////////////////////////////////preparing blob metadat////////////////////
                function prepareBlob(blob){
                            // generating a random file name
                             fileName = getFileName('webm');
                             // we need to upload "File" --- not "Blob"
                             fileObject = new File([blob], fileName, {
                             type: 'video/webm'
                         });
                }
                function InitUploading()
                             {
                    uploadToPHPServer(fileObject, function (response, fileDownloadURL) {
                            if (response !== 'ended') {
                            document.getElementById('header').innerHTML = response; // upload progress
                            return;
                            }
                             document.getElementById('header').innerHTML = '<a href="' + fileDownloadURL +
                                '" target="_blank">' +
                                                     fileDownloadURL + '</a>';
                            //alert('Successfully uploaded recorded blob.');
                            // preview uploaded file
                            video.src = fileDownloadURL;
                            // open uploaded file in a new tab
                            window.open(fileDownloadURL);
                            });
                             }

                             function uploadToPHPServer(blob, callback) {
                                     // create FormData
                                     var formData = new FormData();
                                     formData.append('video-filename', blob.name);
                                     formData.append('video-blob', blob);
                                     callback('Uploading recorded-file to server.');
                                     makeXMLHttpRequest('save.php', formData, function (progress) {
                                             if (progress !== 'Upload Complete') {
                                                     callback(progress);
                                                     return;
                                             }
                                            // var initialURL = 'uploads/' + blob.name;
                                             callback('ended', initialURL);
                                     });
                             }
                  ///////////////////////////////////////////////////////////////////////////////////

                        function makeXMLHttpRequest(url, data, callback) {
                            var request = new XMLHttpRequest();
                            request.onreadystatechange = function () {
                                if (request.readyState == 4 && request.status == 200) {
                                    if (request.responseText === 'success') {
                                        callback('Upload Complete');
                                        return;
                                    }
                                    //alert(request.responseText);

                                    window.location.href = 'index.html';
                        return;

                                }
                            };
                            request.upload.onloadstart = function () {
                                callback('Upload Begins...');
                            };
                            request.upload.onprogress = function (event) {
                                callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
                            };
                            request.upload.onload = function () {
                                callback('Progress Ending');
                            };
                            request.upload.onload = function () {
                                callback('Upload Complete');
                            };
                            request.upload.onerror = function (error) {
                                callback('Upload Failed.');
                            };
                            request.upload.onabort = function (error) {
                                callback('Upload Aborted.');
                            };
                            request.open('POST', url);
                            request.send(data);
                        }
                        // this function is used to generate random file name
                        function getFileName(fileExtension) {
                            var d = new Date();
                            var year = d.getUTCFullYear();
                            var month = d.getUTCMonth() +1;
                            var date = d.getUTCDate();
                            return 'ISelfie-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
                        }

                        function getRandomString() {
                            if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
                                var a = window.crypto.getRandomValues(new Uint32Array(3)),
                                    token = '';
                                for (var i = 0, l = a.length; i < l; i++) {
                                    token += a[i].toString(36);
                                }
                                return token;
                            } else {
                                return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
                            }

                        }
                         if (!navigator || !navigator.getUserMedia || !navigator.mediaDevices.getUserMedia) {
                        if (window.confirm('Your browser does not support WebVideo, try Google/Chrome'))
                        {
                         window.location.href='.....com';
                                            } else {
                                                startCamera();
                        }
                        }
                  navigator
                    .mediaDevices
                    .getUserMedia({audio: true, video: true })
                    .then(initRecorder)
                    .catch(console.error)

Any assistance is appreciated.
 

Top