上传视频文件使用JavaScript分块上传和PHP处理10MB以上的文件时出现问题。

huangapple go评论57阅读模式
英文:

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

问题

这是您提供的JavaScript和PHP代码的翻译部分。如果需要进一步的问题解答,请告诉我。

JavaScript代码:

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); // 设置块大小为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 = "完成";
  } 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 // 正确的块索引
          );
          Remainder = Remainder - chunkSize;
        } else {
          chunk = TheFile.slice(
            chunkId * chunkSize,
            filesize // 包括结束索引
          );
          Remainder = 0;
        }

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

        xrequest.onerror = () => {
          console.error("发送HTTP请求时出错。");
        };

        xrequest.upload.addEventListener("error", () => {
          console.error("上传文件时出错。");
        });

        xrequest.upload.addEventListener("abort", () => {
          console.error("上传被取消。");
        });

        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("未选择文件。");
  }
}

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

PHP代码:

<?php
$sizeFile = '';
$chunkSize = 1024 * 1024; // 设置块大小为1MB

// 检查是否设置了所有必需的参数
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']));

    // 质量检查
    if (file_exists($target_file)) {
        echo "错误:文件已存在";
        $GoAhead = 0;
    }

    if ($_FILES['chunk']['size'] > $chunkSize) {
        echo "错误:文件太大。最大文件大小为1MB。";
        $GoAhead = 0;
    }

    if (!$checksum) {
        echo '错误:无效的块数据';
        $GoAhead = 0;
    }

    if (file_exists($chunkPath)) {
        echo '错误:文件已存在';
        $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 "错误:质量检查失败";
                $GoAhead = 0;
            }
            if (count($chunks) != $_POST['totalNumber']) {
                echo '下一个';
            }

            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 '文件上传成功。';
            } else {
                echo count($chunks) == intval($_POST['totalNumber']) . '//';
            }
        } else {
            echo '错误:上传文件';
        }
    }
} else {
    echo '错误:缺少必需的参数';
}
?>

请注意,以上翻译可能不包括所有问题或潜在错误。如果您需要帮助解决问题,可能需要进行更详细的调试和分析。

英文:

`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(&quot;#upload-button&quot;);
const file = document.querySelector(&quot;#file-input&quot;);
const barlen = document.querySelector(&quot;.progress-bar-fill&quot;);
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(&quot;--len&quot;, totalPercentComplete + &quot;%&quot;);
if (totalPercentComplete == 100) {
barlen.innerHTML = &quot;complete&quot;;
} 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 &gt; 0) {
for (let chunkId = 0; chunkId &lt; number_allowed_chunks; chunkId++) {
chunkIndex++;
if (Remainder &gt; 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(&quot;POST&quot;, &quot;chatphp.php&quot;, true);
xrequest.onerror = () =&gt; {
console.error(&quot;Error sending HTTP request.&quot;);
};
xrequest.upload.addEventListener(&quot;error&quot;, () =&gt; {
console.error(&quot;Error uploading file.&quot;);
});
xrequest.upload.addEventListener(&quot;abort&quot;, () =&gt; {
console.error(&quot;Upload aborted.&quot;);
});
xrequest.upload.addEventListener(&quot;progress&quot;, ({ loaded, total }) =&gt; {
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(&quot;chunk&quot;, chunk);
formData.append(&quot;chunkIndex&quot;, chunkIndex);
formData.append(&quot;fileName&quot;, filename);
formData.append(&quot;totalNumber&quot;, number_allowed_chunks);
xrequest.send(formData);
}
}
} else {
console.error(&quot;No file selected.&quot;);
}
}
file.onchange = () =&gt; processFile();

and here's the php file

&lt;?php
$sizeFile = &#39;&#39;;
$chunkSize = 1024 * 1024; // Set chunk size to 1MB
// Check if all required parameters are set
if (isset($_POST[&#39;totalNumber&#39;]) &amp;&amp; isset($_POST[&#39;chunkIndex&#39;]) &amp;&amp; isset($_POST[&#39;fileName&#39;]) &amp;&amp; isset($_FILES[&#39;chunk&#39;]) &amp;&amp; $_FILES[&#39;chunk&#39;][&quot;error&quot;] == UPLOAD_ERR_OK) {
$filename = $_POST[&#39;fileName&#39;];
$fileIndex = $_POST[&#39;chunkIndex&#39;];
$targetDir = &#39;uploads/&#39;;
$GoAhead = 1;
$target_file = $targetDir . basename($_FILES[&#39;chunk&#39;][&#39;name&#39;]);
$chunkPath = $targetDir . $filename . &#39;.&#39; . $fileIndex;
$checksum = md5(file_get_contents($_FILES[&#39;chunk&#39;][&#39;tmp_name&#39;]));
///////////////quality inspection
if (file_exists($target_file)) {
echo &quot;Error: File already exists&quot;;
$GoAhead = 0;
}
if ($_FILES[&#39;chunk&#39;][&#39;size&#39;] &gt; $chunkSize) {
echo &quot;Error: File too large. Maximum file size is 1MB.&quot;;
$GoAhead = 0;
}
if (!$checksum) {
echo &#39;Error: Invalid chunk data&#39;;
$GoAhead = 0;
}
if (file_exists($chunkPath)) {
echo &#39;Error: File already exists&#39;;
$GoAhead = 0;
}
if ($GoAhead == 1) {
if (move_uploaded_file($_FILES[&#39;chunk&#39;][&#39;tmp_name&#39;], $chunkPath)) {
$chunks = glob($targetDir . $filename . &#39;.*&#39;);
$uploadedChunkFile = md5_file($chunkPath);
if ($uploadedChunkFile != $checksum) {
echo &quot;Error: Quality check failed&quot;;
$GoAhead = 0;
}
if (count($chunks) != $_POST[&#39;totalNumber&#39;]) {
echo &#39;Next&#39;;
}
if ($GoAhead == 1 &amp;&amp; count($chunks) == $_POST[&#39;totalNumber&#39;]) {
$filePath = $targetDir . $filename;
$fileProcessor = fopen($filePath, &#39;w&#39;);
for ($i = 0; $i &lt; count($chunks); $i++) {
fwrite($fileProcessor, file_get_contents($chunks[$i]));
unlink($chunks[$i]);
}
fclose($fileProcessor);
echo &#39;File uploaded successfully.&#39;;
} else {
echo count($chunks) == intval($_POST[&#39;totalNumber&#39;]) . &#39;//&#39;;
}
} else {
echo &#39;Error: Uploading file&#39;;
}
}
} else {
echo &#39;Error: Missing required parameters&#39;;
}
?&gt;

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

答案1

得分: 0

增加PHP内存限制。使用PHP函数ini_set('memory_limit','2048M');或php.ini。

英文:

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

huangapple
  • 本文由 发表于 2023年5月7日 09:43:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定