How to upload videos using javascript and php?

by filiberto , in category: PHP General , 9 months ago

How to upload videos using javascript and php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , a month ago

@filiberto 

To upload videos using JavaScript and PHP, you can follow these steps:

  1. Create a form in your HTML file that includes a file input field for the user to select the video file they want to upload:
1
2
3
4
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="videoFile" id="videoFile">
    <button type="submit">Upload</button>
</form>


  1. Create an upload.php file on your server to handle the file upload. In the upload.php file, use PHP to move the uploaded video file to a specific directory on your server:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
$uploadDir = 'videos/';
$uploadFile = $uploadDir . basename($_FILES['videoFile']['name']);

if (move_uploaded_file($_FILES['videoFile']['tmp_name'], $uploadFile)) {
    echo "File is valid, and was successfully uploaded.
";
} else {
    echo "Possible file upload attack!
";
}
?>


  1. Use JavaScript to handle the form submission and send the video file to the upload.php file using AJAX:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
document.getElementById('uploadForm').addEventListener('submit', function(event) {
    event.preventDefault();
    
    var formData = new FormData(this);
    
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'upload.php', true);
    
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            console.log(xhr.responseText);
        }
    };
    
    xhr.send(formData);
});


  1. Make sure to set the correct permissions on the directory where you want to store the uploaded videos so that the PHP script can move the video file successfully.


By following these steps, you can create a simple video upload functionality using JavaScript and PHP.