javascriptphpchunking

uploaded video file with js chunking upload and php not working for file abve 10mb


`i tried writing a chunk upload code with js and php, it works fine when you upload a video file less than a 10mb but uploading a video file 17.6mb, the file uploads with it maintains it appropriate size but the video file cant play, wrote error handlers in php and js, but no there was no error. heres the js code

const uploadInput = document.querySelector("#upload-button");
const file = document.querySelector("#file-input");
const barlen = document.querySelector(".progress-bar-fill");
let reader = new FileReader();
const chunkSize = 1 * (1024 * 1024); // Set chunk size to 1MB

let totalevent = 0;
let currentevent = 0;

function updateProgress(loaded, total, numberofChunks, chunkCounter) {
  const percentComplete = Math.round((loaded / total) * 100);
  const totalPercentComplete = Math.round(
    ((chunkCounter - 1) / numberofChunks) * 100 +
      percentComplete / numberofChunks
  );

  barlen.style.setProperty("--len", totalPercentComplete + "%");

  if (totalPercentComplete == 100) {
    barlen.innerHTML = "complete";
  } else {
    barlen.innerHTML = totalPercentComplete;
  }
}

function processFile() {
  if (file.files[0]) {
    const TheFile = file.files[0];
    const filename = file.files[0].name;
    const filesize = file.files[0].size;
    let Remainder = filesize;
    let chunk = new Blob();
    let chunkIndex = 0;
    const number_allowed_chunks = Math.ceil(filesize / chunkSize);

    if (Remainder > 0) {
      for (let chunkId = 0; chunkId < number_allowed_chunks; chunkId++) {
        chunkIndex++;

        if (Remainder > chunkSize) {
          chunk = TheFile.slice(
            chunkId * chunkSize,
            (chunkId + 1) * chunkSize // Correct chunk index
          );
          Remainder = Remainder - chunkSize;
        } else {
          chunk = TheFile.slice(
            chunkId * chunkSize,
            filesize // Include end index
          );
          Remainder = 0;
        }

        const xrequest = new XMLHttpRequest();
        xrequest.open("POST", "chatphp.php", true);

        xrequest.onerror = () => {
          console.error("Error sending HTTP request.");
        };

        xrequest.upload.addEventListener("error", () => {
          console.error("Error uploading file.");
        });

        xrequest.upload.addEventListener("abort", () => {
          console.error("Upload aborted.");
        });

        xrequest.upload.addEventListener("progress", ({ loaded, total }) => {
          const fileloaded = Math.floor((loaded / total) * 100);
          const uploaded = Math.floor(total / 1000);
          updateProgress(loaded, total, number_allowed_chunks, chunkIndex);
        });

        const formData = new FormData();
        formData.append("chunk", chunk);
        formData.append("chunkIndex", chunkIndex);
        formData.append("fileName", filename);
        formData.append("totalNumber", number_allowed_chunks);
        xrequest.send(formData);
      }
    }
  } else {
    console.error("No file selected.");
  }
}

file.onchange = () => processFile();

and here's the php file

<?php
$sizeFile = '';
$chunkSize = 1024 * 1024; // Set chunk size to 1MB

// Check if all required parameters are set
if (isset($_POST['totalNumber']) && isset($_POST['chunkIndex']) && isset($_POST['fileName']) && isset($_FILES['chunk']) && $_FILES['chunk']["error"] == UPLOAD_ERR_OK) {
    $filename = $_POST['fileName'];
    $fileIndex = $_POST['chunkIndex'];
    $targetDir = 'uploads/';
    $GoAhead = 1;
    $target_file = $targetDir . basename($_FILES['chunk']['name']);
    $chunkPath = $targetDir . $filename . '.' . $fileIndex;
    $checksum = md5(file_get_contents($_FILES['chunk']['tmp_name']));

    ///////////////quality inspection
    if (file_exists($target_file)) {
        echo "Error: File already exists";
        $GoAhead = 0;
    }

    if ($_FILES['chunk']['size'] > $chunkSize) {
        echo "Error: File too large. Maximum file size is 1MB.";
        $GoAhead = 0;
    }

    if (!$checksum) {
        echo 'Error: Invalid chunk data';
        $GoAhead = 0;
    }

    if (file_exists($chunkPath)) {
        echo 'Error: File already exists';
        $GoAhead = 0;
    }

    if ($GoAhead == 1) {
        if (move_uploaded_file($_FILES['chunk']['tmp_name'], $chunkPath)) {
            $chunks = glob($targetDir . $filename . '.*');
            $uploadedChunkFile = md5_file($chunkPath);
            if ($uploadedChunkFile != $checksum) {
                echo "Error: Quality check failed";
                $GoAhead = 0;
            }
            if (count($chunks) != $_POST['totalNumber']) {
                echo 'Next';
            }

            if ($GoAhead == 1 && count($chunks) == $_POST['totalNumber']) {
                $filePath = $targetDir . $filename;
                $fileProcessor = fopen($filePath, 'w');
                for ($i = 0; $i < count($chunks); $i++) {
                    fwrite($fileProcessor, file_get_contents($chunks[$i]));
                    unlink($chunks[$i]);
                }
                fclose($fileProcessor);
                echo 'File uploaded successfully.';
            } else {
                echo count($chunks) == intval($_POST['totalNumber']) . '//';
            }
        } else {
            echo 'Error: Uploading file';
        }
    }
} else {
    echo 'Error: Missing required parameters';
}
?>

Is there an issue with the cod or better still can you help me find the possible issue causing this.


Solution

  • Increase php memory limit. Use php function ini_set('memory_limit','2048M'); or php.ini.