• 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 javascript

chrisj

Coder
Thanks for all of your previous help.
I am testing this new code, where video is captured/recorded successfully. However, I don’t have the upload part correct. Nothing happens upon selecting the upload button:

HTML:
<button id="button1" onclick="startRecording()">Start</button>
<button id="button2" onclick="endRecording()">Stop</button>
<button id="fileupload">Upload File</button>
<video id="video" autoplay="autoplay" controls="controls" poster="/thumbnail.jpg" type="video/mp4" muted playsInline><source src="source.mp4" type="video/mp4"></video>

and the js:
JavaScript:
function supportsRecording(mimeType)
{
    if (!window.MediaRecorder)
        return false;
    if (!MediaRecorder.isTypeSupported)
        return mimeType.startsWith("audio/mp4") || mimeType.startsWith("video/mp4");
    return MediaRecorder.isTypeSupported(mimeType);
}

var video = document.querySelector('#video');

let blobs = [];
let stream;
let mediaRecorder;
async function startRecording()
{
    stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
    mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.ondataavailable = (event) => {
       // Let's append blobs for now, we could also upload them to the network.
       if (event.data)
            blobs.push(event.data);
    }
    mediaRecorder.onstop = doPreview;
    // Let's receive 1 second blobs
    mediaRecorder.start(1000);
}
function endRecording()
{
    // Let's stop capture and recording
    mediaRecorder.stop();
    stream.getTracks().forEach(track => track.stop());
}
function doPreview()
{
    if (!blobs.length)
        return;
    // Let's concatenate blobs to preview the recorded content
    video.src = URL.createObjectURL(new Blob(blobs, { type: mediaRecorder.mimeType }));
}

//////////////////////////////////////////////////////////////////////////////////////////////////

async function uploadFile() {
    let formData = new FormData();
    formData.append("file", fileupload.files[0]);
    await fetch('/upload.php', {
      method: "POST",
      body: formData
    });
    alert('The file has been uploaded successfully.');
}


any assistance is appreciated
 

Mutiny

Active Coder
Change your code like this, at line 16:

Code:
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
die("My extension is: " . $extension);

That will stop execution of your script and should also output the extension you are expecting given the file you uploaded. If all is working as it should, you should see:

"My extension is webm".

Since you're doing an AJAX upload, you will have to open your browser's inspector via right clicking on "Inspect" or "Inspect Element", then go to the network tab and watch for the network request where you save the file.
 

chrisj

Coder
Thank you very much.
I ran the code like this, as instructed:

PHP:
<?php
foreach (array('video', 'audio') as $type) {
    if (isset($_FILES["${type}-blob"])) {

        $fileName = $_POST["${type}-filename"];
        $uploadDirectory = 'uploads/' . $fileName;

            // make sure that one can upload only allowed audio/video files
            $allowed = array(
                'webm',
                'wav',
                'mp4',
                'mov'
    );

    $extension = pathinfo($filePath, PATHINFO_EXTENSION);
    die("My extension is: " . $extension);

   if (!$extension || empty($extension) || !in_array($extension, $allowed)) {
        echo 'Invalid file extension: '.$extension;
       return;
 }
        if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
            echo (" problem moving uploaded file");
        }
    }
}
?>

and after I select 'Upload' I see dialog box pop up and it shows "My extension is" only.

So, I look at dev tools >Console > Elements and I see this:

HTML:
<video id="video" autoplay="true" controls="" muted="" playsinline="" src="blob:https://websitename.com/1145a414-36d7-4a27-880d-779f48f20210"></video>

I hope this info helps to be able to provide a little more assistance. Thanks again
 

chrisj

Coder
Thanks again for your previous help, this successfully showed "My extension is webm":

PHP:
           $extension = pathinfo($uploadDirectory, PATHINFO_EXTENSION);
            die("My extension is: " . $extension);

Then I replaced webm with jpg like so (and tested):

PHP:
            $allowed = array(
                'jpg',
                'wav',
                'mp4',
                'mov'

And upon uploading a webm file, it displays : Invalid file extension: webm

All good. So, now I'm wondering if I can add/integrate this code somewhere other than js because you said "you shouldn't rely on the Javascript, which anyone can edit, for security":

JavaScript:
               var fileName = generateRandomString() + '.webm';

                    // 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 'Record-' + 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, '');
                        }
                    }
I look forward to your feedback or better suggestion.
 

Mutiny

Active Coder
Try this, take this code:

PHP:
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
    echo (" problem moving uploaded file");
}

Replace with:

PHP:
$new_filepath = "/uploads/" . uniqid() . ".". $extension;

if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $new_filepath)) {
    echo (" problem moving uploaded file");
}

What this does is it saves the file with a unique ID using the uniqid function. This accomplishes roughly the same thing as your Javascript code, but is more secure since it's done on the server level. When you upload a file, you should now have a file generated with a unique ID, so no two files should now have the same filename.
 

Mutiny

Active Coder
Ah, I had an extra slash at the beginning of the uploads directory path. Try changing:

PHP:
$new_filepath = "/uploads/" . uniqid() . ".". $extension;

to:

PHP:
$new_filepath = "uploads/" . uniqid() . ".". $extension;
 

chrisj

Coder
Ah, I had an extra slash at the beginning of the uploads directory path. Try changing:

PHP:
$new_filepath = "/uploads/" . uniqid() . ".". $extension;

to:

PHP:
$new_filepath = "uploads/" . uniqid() . ".". $extension;

Thank you for your reply. It works. Much appreciared. But, of course I have another question;
now that it generates a unique file name, what should I do with the var fileName line in my js:

JavaScript:
function uploadFile() {
      // create FormData
      var fileType = 'video'; // or "audio"
      var fileName = 'WXYZ.webm';

I look forward to your reply.
 

Mutiny

Active Coder
You might need to leave the filename in the JS as-is. Because you're essentially faking an upload of a file from the Javascript, you need a filename you can pass to the PHP script, same as if the user were to hit browse and pick a file from their hard drive.
 

Top